Expand variables in sed

I need to use sed in a bash script, to add lines after any line number from a script with some pair of values ​​(below work)

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

But I need on a bash (sh) script to expand variables (below does not work)

 sed -i.bak '$number_linei\$var1=$var2' $var3 
+6
source share
2 answers

Just use double quotes instead of single quotes. You also need to use {} to properly delineate the variable number_line and exit \ too.

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

I personally would prefer that all variables use {} , eventually something like:

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

Change single quotes to double quotes:

man bash :

  Enclosing characters in single quotes preserves the literal value of each character within the quotes. Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes. 
+1
source

Source: https://habr.com/ru/post/948742/


All Articles