Bash – Insert word between each matching line

bashlinuxshell

I am wondering how I can check the end of the file in while loop.
What I am doing here is if there is some word, such as, "pineapple", "apple", "onion", "orange", or etc, I want to find lines including specific words by using grep command and make some comment "window". For example, if I use grep 'a' 'file', then it will find "pineapple", "apple", and "orange". Then, finally I want to make it printed like "pineapple, window, apple, window, orange, window", something like this. So, I would like to make some condition in while or for loop. Any helps will be really appreciated.

edit:
Sample inputs

apple
banana
pineapple
orange
mandu
ricecake
meat
juice
milk
onion
green onion

Expected outputs when using grep command –> grep 'a' 'file name'

apple
window
banana
window
pineapple
window
orange
window
mandu
window
ricecake
window
meat
window

Best Answer

Using awk

To print window after every line that matches a:

$ awk '/a/{print; print "window"}' filename
apple
window
banana
window
pineapple
window
orange
window
mandu
window
ricecake
window
meat
window

How it works

/a/{...} selects lines that match the regex a. For each such line, the commands in curly braces are executed.

print prints the line containing the match

print "window" prints window.

Using sed

$ sed -n '/a/{s/$/\nwindow/; p}' filename
apple
window
banana
window
pineapple
window
orange
window
mandu
window
ricecake
window
meat
window

How it works

-n tells sed not to print unless we explicitly as it to.

/a/{...} selects lines that match the regex a. For those lines, the commands in curly braces are executed.

s/$/\nwindow/ adds a newline and window after the end of the current line.

p prints.

Related Question