简体   繁体   English

为什么变量替换在这种awk单行代码中起作用?

[英]Why does variable substitution work in this awk one-liner?

The Internet says that to use a shell variable in Awk, you can either double-quote the Awk program (which is a bad idea), or use Awk's variable-passing mechanism (which is the correct approach). 互联网上说,要在Awk中使用shell变量,可以将Awk程序双引号(这是一个坏主意),也可以使用Awk的变量传递机制(这是正确的方法)。

Why then do I get this? 为什么然后我得到这个?

$ export name=Andrew
$ echo 'hello' | awk '{system("echo ${name}, " $1)}'
Andrew, hello

Is it because Awk spawns a shell to execute the system command, the variable substitution is interpreted by that shell rather than by Awk, and that shell, being a sub-shell of the shell that launched Awk, inherits its shell variables? 是因为Awk产生了执行system命令的外壳程序,变量替换是由该外壳程序而不是Awk解释的,并且该外壳程序是启动Awk的外壳程序的子外壳程序,因此继承了其外壳程序变量?

awk passes the literal string echo ${name}, hello to the system shell to process. awk将文字字符串echo ${name}, hello传递给系统外壳进行处理。 Because you exported name prior to calling awk , name=Andrew appears in awk 's environment, and awk passes it on to the system shell in turn. 因为您在调用awk之前导出了name ,所以name=Andrew出现在awk的环境中,并且awk依次将其传递给系统外壳。 The shell then is able to expand ${name} to Andrew as a result. 这样,shell便可以将${name}扩展到Andrew。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM