在AWK表达式中使用bash变量 [英] Use bash variable in AWK expression
问题描述
我在shell脚本中尝试了以下代码段,但awk
找不到$REF
I tried the following snippet in a shell script but awk
didn't find $REF
REF=SEARCH_TEXT
echo "some text" | awk '/$REF/{print $2}'
推荐答案
您的问题的措辞是真的很差...
You question is worded really poor...
无论如何,我想你想要这个:
Anyway, I think you want this:
REF=SEARCH_TEXT
echo "some text" | awk "/$REF/{print \$2}"
请注意$2
的转义和双引号.
Note the escaping of $2
and the double quotes.
或者这个:
REF=SEARCH_TEXT
echo "some text" | awk "/$REF/"'{print $2}'
请注意谨慎使用双引号和单引号,并且不要在$2
上转义.
Note the judicious use of double and single quotes and no escaping on $2
.
您必须使用shell扩展,否则将包括导出shell变量并从awk的环境中使用它-在这种情况下,这是 overkill :
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 overkill in this situation:
export REF=SEARCH_TEXT
echo "some text" | awk '{if (match($0, ENVIRON["REF"])) print $2}'
我认为awk不支持/.../卫队中的变量. 如果我错了,请纠正我.
I think awk does not support variables in /.../ guards. Please correct me if I'm wrong.
这篇关于在AWK表达式中使用bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!