在 AWK 表达式中使用 bash 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4519408/
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-17 23:09:50  来源:igfitidea点击:

Use bash variable in AWK expression

bashvariablesawkscriptingescaping

提问by vehomzzz

I tried the following snippet in a shell script but awkdidn't find $REF

我在 shell 脚本中尝试了以下代码段,但awk没有找到$REF

REF=SEARCH_TEXT
echo "some text" | awk '/$REF/{print }'

回答by glenn Hymanman

Instead of quoting games in the shell, use the -voption to pass the shell variable as an awk variable:

不要在 shell 中引用游戏,而是使用-v选项将 shell 变量作为 awk 变量传递:

awk -v ref="$REF" 'match(
REF=SEARCH_TEXT
echo "some text" | awk "/$REF/{print $2}"
, ref) {print }'

If $REFis just text and not a regular expression, use the index()function instead of match().

如果$REF只是文本而不是正则表达式,请使用index()函数而不是match().

回答by Marcus Borkenhagen

You question is worded reallypoor...

你问题的措辞真是可怜...

Anyway, I think you want this:

无论如何,我认为你想要这个:

REF=SEARCH_TEXT
echo "some text" | awk "/$REF/"'{print }'

Note the escaping of $2and the double quotes.

注意转义$2和双引号。

or this:

或这个:

export REF=SEARCH_TEXT
echo "some text" | awk '{if (match(##代码##, ENVIRON["REF"])) print }'

Note the judicious use of double and single quotes and no escaping on $2.

请注意双引号和单引号的明智使用,并且不要在$2.

You have to use shell expansion, as otherwise it would encompass exporting a shell variable and using it from the environment with awk - which is overkillin this situation:

您必须使用 shell 扩展,否则它将包含导出 shell 变量并从环境中使用 awk 使用它 - 这在这种情况下是过度的

##代码##

I think awk does not support variables in /.../ guards. Please correct me if I'm wrong.

我认为 awk 不支持 /.../ 守卫中的变量。如果我错了,请纠正我。

回答by Andrew Beals

In gawk, you have the ENVIRONarray, e.g. awk 'END{print ENVIRON["REF"]}' /dev/nullwill print your variable if you've exported it out from the shell to sub-processes.

在 中gawk,您有ENVIRON数组,例如,awk 'END{print ENVIRON["REF"]}' /dev/null如果您已将export其从外壳程序编辑到子进程,则将打印您的变量。