Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand variables in sed

I need use sed into bash script, for add lines after any line numer of script with some pair of values (below work)

sed -i.bak '14i\some_text=some_text' file

But I need on script bash (sh) for expand variables (below not work)

sed -i.bak '$number_linei\$var1=$var2' $var3
like image 343
abkrim Avatar asked Jul 04 '13 20:07

abkrim


People also ask

How do you expand a variable inside an sed?

Just use double quotes instead of single quotes. You'll also need to use {} to delimit the number_line variable correctly and escape the \ , too.

How do you use sed on a variable?

Another way to feed a literal text or a variable to stdin is by using here-string: $ sed 's/We/They/; s/Linux/Microsoft Windows/' <<< "We love Linux." They love Microsoft Windows. $ sed 's/We/They/; s/Linux/Microsoft Windows/' <<< $TEXT They love Microsoft Windows.


1 Answers

Just use double quotes instead of single quotes. You'll also need to use {} to delimit the number_line variable correctly and escape the \, too.

sed -i.bak "${number_line}i\\$var1=$var2" $var3

I'd personally prefer to see all of the variables use the {}, ending up with something like:

sed -i.bak "${number_line}i\\${var1}=${var2}" ${var3}
like image 155
Carl Norum Avatar answered Sep 28 '22 07:09

Carl Norum