maosen zhou
maosen zhou

Reputation: 11

sed not working in read while loop

I am using read to make some file in a while loop. The code is:

while read var val
do
 sed -i 's/$var/$val/g' Hhh300_4L_gen.sh
 echo $var $val
done < "Hhh300_4L_config.txt"

Where in Hhh300_4L_config.txt, there is a line, for instance,

PROCESSNAME Hhh;

and in Hhh300_4L_gen.sh, there is one element: PROCESSNAME. So if it works, PROCESSNAME in Hhh300_4L_gen.sh should be replaced by Hhh. But it doesn't. However the output of echo prints correctly.

Upvotes: 1

Views: 1228

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14490

Variables are not expanded inside single quotes. If you want var and val to expand you need double quotes (and make sure they don't have the sed separator, here / in them):

sed -i "s/$var/$val/g" Hhh300_4L_gen.sh

though if you're modifying a shell script (as I'm guessing might be from the .sh) there are probably better ways to do it, like having your .txt file store things as var=val instead of with white space separating them, then just source it from the script.

Upvotes: 3

Related Questions