bash 在 sed 中展开变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17477890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:50:20  来源:igfitidea点击:

Expand variables in sed

bashvariablessed

提问by abkrim

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

我需要在 bash 脚本中使用 sed,以便在具有一些值对的脚本的任何行号之后添加行(下面的工作)

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

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

但是我需要脚本 bash (sh) 来扩展变量(下面不起作用)

sed -i.bak '$number_linei$var1=$var2' $var3

回答by Carl Norum

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

只需使用双引号而不是单引号。您还需要使用{}number_line正确分隔变量并转义\

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

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

我个人更喜欢看到所有变量都使用{},最终得到如下结果:

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

回答by Lev Levitsky

Change single quotes to double quotes:

将单引号改为双引号:

man bash:

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.