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