bash 如何在awk中打​​印变量

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

How to print variable inside awk

bashscriptingawk

提问by Sharat Chandra

I want the awk to interpret the variable as follows

我希望 awk 解释变量如下

#!/bin/bash

file=tau
f=2.54
order=even

awk '{sum+=}; END {print '${file}_${f}_${order}_v1.xls', sum/NR}'
${file}_${f}_${order}_v1.xls >> safe/P-state-summary.xls

I want the desired output as follows -

我想要如下所需的输出 -

tau_2.54_even_v1.xls   sum/NR

Can anybody help me out with this ?

有人可以帮我解决这个问题吗?

回答by Matt Ryall

First, you need to exportenvironment variables if you want them to be passed in the environment of a child process like awk.

首先,export如果您希望在子进程的环境中传递环境变量,例如awk.

Second, you can use ENVIRON["name"]to get an environment variable in awk. So the following works for me:

其次,您可以使用ENVIRON["name"]awk. 所以以下对我有用:

#!/bin/bash

export file=tau
export f=2.54
export order=even

awk '{sum+=}; END {print ENVIRON["file"] "_" ENVIRON["f"] "_" ENVIRON["order"] "_v1.xls", sum/NR}'

回答by TheBonsai

Don't forget that you can set "AWK variables" on commandline

不要忘记您可以在命令行上设置“AWK 变量”

awk -v FOO=bar '...<AWK code that uses the AWK variable FOO>...'

回答by DigitalRoss

I think this is what you want:

我认为这就是你想要的:

#!/bin/bash

file=tau
f=2.54
order=even

awk "{sum+=$2}; END {print \"${file}_${f}_${order}_v1.xls\", sum/NR}" \
  ${file}_${f}_${order}_v1.xls >> safe/P-state-summary.xls

回答by Sharat Chandra

Well I used a mixture of the above solutions and got it working with this

好吧,我使用了上述解决方案的混合物,并使用了它

printf "\n${file}_${f}_${order}_v1.xls  " >> Safe/P-state-summary.xls
awk '{sum+=}; END  {print sum/NR}' ${file}_${f}_${order}_v1.xls >> Safe/P-state-summary.xls