Loop through file and replace with sed

Hello all,

I need some help please.

I got file1 with names.

foo bar
foo bar
foo bar
foo bar
foo bar

and I got file2 with some text

some text
some text
#KEYWORD

some text
some text
some text

after the #KEYWORD I need to add the following line

email "foo bar" 

in double quotes and basically loop through file1.

#!/bin/sh

while read line
do
sed '/#KEYWORD/a email = "'${line}'"' file2 > file3
# do stuff with file3 and keep looping
sleep 10
done < file1

cat file3

some text
some text
#KEYWORD
email = "foo

some text
some text
some text

Why not some email = "foo bar" ?????

Thanks guys

That is because $line is used unquoted and thus subject to field splitting by the shell (so only the first field will be part of the sed script in quotes).

Try:

sed "/#KEYWORD/a email = \"${line}\"" file2
...
done < file1 >file3

---
Note: Only GNU sed supports the append (a) command like this..

1 Like

Thanks ever so much

With other quote type and standard sed syntax

sed '/#KEYWORD/a\
email = "'"${line}"'"' file2 > file3