bash 如何在 awk 表达式中使用变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2599051/
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
How to use a variable in an awk expression
提问by lugte098
I'm trying to make this command:
我正在尝试执行此命令:
sed bla bla filename | awk '{printf "%s %s_entry_%.3f %.3f %.3f %.3f",,,,,,}'
But the thing is, i want the %.3f part to be variable. So in one case it could be %.3f and in another it could be %.3f %.3f %.3f. So i'll just use a static one in my example code for clarity. So if i want 4 of these %.3f and put them in variable $values like so:
但问题是,我希望 %.3f 部分是可变的。因此,在一种情况下,它可能是 %.3f,而在另一种情况下,它可能是 %.3f %.3f %.3f。所以为了清楚起见,我将在我的示例代码中使用静态的。因此,如果我想要其中的 4 个 %.3f 并将它们放入变量 $values 中,如下所示:
values="%.3f %.3f %.3f %.3f"
Then how can I put this string in the awk expression, without making awk to just put literally "${values}" in there. The following is my non-working-attempt:
那么我怎么能把这个字符串放在 awk 表达式中,而不是让 awk 只是把“${values}”放在那里。以下是我的非工作尝试:
sed bla bla filename | awk '{printf "%s %s_entry_${values}",,,,,,}'
回答by ghostdog74
you can use -voption of awk to pass in variable from the shell
您可以使用-vawk 选项从 shell 传入变量
#!/bin/bash
awk -v values="${values}" '{gsub("blah","replace");printf "%s %s_entry_"values ....}' file
the gsub()function is to replace what you have with that sedcommand. So just one awk command will do. sedis redundant in this case (and most other cases where awk is used)
该gsub()功能是代替你有什么sed命令。所以只需一个 awk 命令就可以了。sed在这种情况下是多余的(以及使用 awk 的大多数其他情况)
回答by Ignacio Vazquez-Abrams
Easiest to use actual awk variables:
最容易使用实际的 awk 变量:
sed bla bla filename | awk -v values="$values" '{printf "%s %s_entry_"values,,,,,,}'
Or with bash:
或者使用 bash:
awk -v values="$values" '{printf "%s %s_entry_"values,,,,,,}' <(sed bla bla filename)
回答by Marcelo Cantos
If you mean that valuesis a shell variable, then this will work:
如果您的意思是这values是一个 shell 变量,那么这将起作用:
sed bla bla filename | awk '{printf "%s %s_entry_"ENVIRON["values"],,,,,,}'

