如何将命令行参数传递到awk脚本中?

时间:2020-04-10 23:08:47

标签: bash awk

我在这里有一个awk脚本:

    BEGIN { count=0;sum=0;thresh_count=0; 
thresh=ARGV[2]} $3=="3"{count++;print $2,$1,$4,$5;sum+=$5;if($5>=thresh)thresh_count++} 
    END {if(NR>0)print "\nThe average grade for the class is "sum/count".";
    print "Number of grades past threshold: " thresh_count;}

并且我希望能够从命令行将参数传递给变量'thresh'。

当我输入时:

awk -f script.awk input.txt 90

但是,进入终端时,出现错误消息“ 90”不是文件或目录。我如何才能将其作为参数传递给“ 90”,而不是尝试将其作为运行脚本的其他文件读取? 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

脚本后的参数被视为要处理的文件。用ARGV读取它们并不会改变。

您使用-v选项设置awk变量。

awk -f script.awk -v thresh=90 input.txt