我需要在bash脚本中使用sed,在脚本的任何行数和一些值之后添加行(在工作之下)
sed -i.bak '14i\some_text=some_text' file
但是我需要脚本bash(sh)来扩展变量(下面不起作用)
sed -i.bak '$number_linei\$var1=$var2' $var3
答案 0 :(得分:14)
只需使用双引号而不是单引号。您还需要使用{}
正确分隔number_line
变量并转义\
。
sed -i.bak "${number_line}i\\$var1=$var2" $var3
我个人更愿意看到所有变量都使用{}
,最后得到的结果如下:
sed -i.bak "${number_line}i\\${var1}=${var2}" ${var3}
答案 1 :(得分:1)
将单引号更改为双引号:
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.