如何将bash参数传递给awk脚本? [英] How to pass bash parameter to awk script?
问题描述
#!/ bin / awk -f
BEGIN {
}
{
filetime [$'$ colnumber'] ++;
}
END {
for(i in filetime){
print filetime [i],i;
#!/ bin / bash
var1 = $ 1
awk -f myawk.awk
运行时:
ls -la | ./countPar.sh 5
收到错误:
ls -la | ./countPar.sh 5
awk:myawk.awk:6:filetime [$'$ colnumber'] ++;
awk:myawk.awk:6:表达式
中无效的字符''''$ <$ $ p
? $ colnumber必须替换为5,所以awk应该读取lsput的第5列。
Thanks。
解决方案您可以直接从命令行将变量传递到您的awk脚本。 b
$ b
更改这一行:
filetime [$'$ colnumber'] ++;
收件人:
FILETIME [colnumber] ++;
并运行:
ls -al | awk -f ./myawk.awk -v colnumber = 5
如果你真的想使用bash包装:
#!/ bin / bash
var1 = $ 1
awk -f myawk.awk colnumber = $ var1
(与上面脚本相同的更改)
如果要使用环境变量,请使用:
#!/ bin / bash
export var1 = $ 1
awk -f myawk.awk
和
filetime [ENVIRON [var1]] ++;
(我真的不明白你的awk脚本的目的是什么,最后一部分可能简化为:
END {print filetime [colnumber],colnumber;}
解析 ls
的输出通常是一个坏主意。)
I have awk file:
#!/bin/awk -f
BEGIN {
}
{
filetime[$'$colnumber']++;
}
END {
for (i in filetime) {
print filetime[i],i;
}
}
And bash script:
#!/bin/bash
var1=$1
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.
解决方案 You can pass variables to your awk script directly from the command line.
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:
#!/bin/bash
var1=$1
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=$1
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:
END { print filetime[colnumber],colnumber; }
and parsing the output of ls
is generally a bad idea.)
这篇关于如何将bash参数传递给awk脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!