bash 在我的 awk 语句中插入变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10054968/
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
inserting variables within my awk statement
提问by Jim
Here is a snippet of my awk statement..I'm trying to insert these 2 variables in the statement but they are not getting evaluated. Can someone point me in the right direction?
这是我的 awk 语句的片段。我试图在语句中插入这 2 个变量,但它们没有得到评估。有人可以指出我正确的方向吗?
ZONE=`date "+%Z %Y"`
DAY=`date "+%a"`
awk '{if (NR<2) {print "[", , "]"}}'
I'm trying this:
我正在尝试这个:
awk '{if (NR<2) {print "[" $DAY, , , , $ZONE "]"}}'
This tip here helped solve my problem.
这里的提示帮助解决了我的问题。
Protect the shell variables from awk by enclosing them with "'" (i.e. double quote - single quote - double quote).
通过用“'”将它们括起来(即双引号 - 单引号 - 双引号)来保护 shell 变量免受 awk 的影响。
awk '{print "'"$VAR1"'", "'"$VAR2"'"}' input_file
awk '{print "'"$VAR1"'", "'"$VAR2"'"}' input_file
回答by yazu
You can use -v option:
您可以使用 -v 选项:
ZONE=`date "+%Z %Y"`
DAY=`date "+%a"`
awk -vzone="$ZONE" -vday="$DAY" 'BEGIN { print zone, day }'
回答by ctt
Those variables won't be expanded where they're enclosed in single quotes. Consider using double quotes for your outermost quotes and escaped double quotes inside your awk expression.
这些变量不会在用单引号括起来的地方展开。考虑对最外层的引号使用双引号,并在 awk 表达式中使用转义双引号。
I'm only guessing here, though, as you do not appear to have included the actual command you used where your variables have been embedded, but aren't being evaluated.
不过,我只是在这里猜测,因为您似乎没有包含您在嵌入变量但未对其进行评估的位置使用的实际命令。
In the future, or if this answer doesn't help, consider including the command you use as well as its output and an explanation of what you expected to happen. This way, it'll be much easier to figure out what you mean.
将来,或者如果此答案没有帮助,请考虑包括您使用的命令及其输出以及您预期发生的情况的解释。这样,就更容易弄清楚你的意思。
回答by Dave Pitts
I liked yazu's answer above, although to get this to work on my MaxOSX (BSD) environment I had to tweak the syntax:
我喜欢上面 yazu 的回答,尽管为了让它在我的 MaxOSX (BSD) 环境中工作,我必须调整语法:
~ $ ZONE=`date "+%Z %Y"`
~ $ DAY=`date "+%a"`
~ $ awk -v zone="$ZONE" -v day="$DAY" 'BEGIN { print zone, day }'
CEST 2018 Wed

