bash 如何将bash参数传递给awk脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8561471/
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 pass bash parameter to awk script?
提问by user710818
I have awk file:
我有 awk 文件:
#!/bin/awk -f
BEGIN {
}
{
filetime[$'$colnumber']++;
}
END {
for (i in filetime) {
print filetime[i],i;
}
}
And bash script:
和 bash 脚本:
#!/bin/bash
var1=
awk -f myawk.awk
When I run:
当我运行时:
ls -la | ./countPar.sh 5
I receive error:
我收到错误:
ls -la | ./countPar.sh 5
awk: myawk.awk:6: filetime[$'$colnumber']++;
awk: myawk.awk:6: ^ invalid char ''' in expression
Why? $colnumber must be replaced with 5, so awk should read 5th column of ls ouput. Thanks.
为什么?$colnumber 必须替换为 5,因此 awk 应该读取 ls 输出的第 5 列。谢谢。
回答by Mat
You can pass variables to your awk script directly from the command line.
您可以直接从命令行将变量传递给 awk 脚本。
Change this line:
改变这一行:
filetime[$'$colnumber']++;
To:
到:
filetime[colnumber]++;
And run:
并运行:
ls -al | awk -f ./myawk.awk -v colnumber=5
If you really want to use a bash wrapper:
如果您真的想使用 bash 包装器:
#!/bin/bash
var1=
awk -f myawk.awk colnumber=$var1
(with the same change in your script as above.)
(与上述脚本中的更改相同。)
If you want to use environment variables use:
如果要使用环境变量,请使用:
#!/bin/bash
export var1=
awk -f myawk.awk
and:
和:
filetime[ENVIRON["var1"]]++;
(I really don't understand what the purpose of your awk script is though. The last part could be simplified to:
(我真的不明白你的 awk 脚本的目的是什么。最后一部分可以简化为:
END { print filetime[colnumber],colnumber; }
and parsing the output of lsis generally a bad idea.)
并且解析 的输出ls通常是一个坏主意。)
回答by Zsolt Botykai
The easiest way to do it:
最简单的方法:
#!/bin/bash
var=
awk -v colnumber="${var}" -f /your/script
But within your awkscript, you don't need the $in front of colnumber.
但是在您的awk脚本中,您不需要$在 colnumber 前面。
HTH
HTH
回答by VIPIN KUMAR
Passing 3 variable to script myscript.sh var1 is the column number on which condition has set. While var2 & var3 are input and temp file.
将 3 变量传递给脚本 myscript.sh var1 是设置条件的列号。而 var2 & var3 是输入和临时文件。
#!/bin/ksh
var1=
var2=
var3=
awk -v col="${var1}" -f awkscript.awk ${var2} > $var3
mv ${var3} ${var2}
execute it like below -
像下面那样执行它 -
./myscript.sh 2 file.txt temp.txt

