17

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

2 Answers 2

30

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}
1
  • A lot of tanks. A bit confuse for me escaping. Work for me
    – abkrim
    Jul 5, 2013 at 7:35
4

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.
2
  • Necessary, but not sufficient to fix the OP's problem.
    – Carl Norum
    Jul 4, 2013 at 20:50
  • A bit confuse for me. If put a ask, it's because, i was try several options. "", '', and dont' work for me. After read first response get a mayor knowledg and I can continue my work.
    – abkrim
    Jul 5, 2013 at 7:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.