我正在尝试查找awk
用于类的第二列数据的平均值。这是我当前的代码,其中包含我的讲师提供的框架:
#!/bin/awk
### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.
# This block of code is executed for each line in the file
{
x=sum
read name
awk 'BEGIN{sum+=$2}'
# The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
# NR is a variable equal to the number of rows in the file
print "Average: " sum/ NR
# Change this to print the Average instead of just the number of rows
}
我收到一条错误消息:
awk: avg.awk:11: awk 'BEGIN{sum+=$2}' $name
awk: avg.awk:11: ^ invalid char ''' in expression
我想我已经很近了,但是我真的不知道从这里去哪里。该代码不应太复杂,因为我们在课堂上看到的一切都是相当基本的。请告诉我。
您的特定错误与第11行有关:
awk 'BEGIN{sum+=$2}'
这是在awk
哪一行被调用,并BEGIN
指定了它的块-但您已经在awk脚本中,因此无需指定awk
。另外,您还希望sum+=$2
在输入的每一行上运行,因此不要在一个BEGIN
块内运行它。因此,该行应简单地读为:
sum+=$2
您也不需要以下行:
x=sum
read name
第一个只是创建了sum
named的同义词x
,我不确定第二个是做什么的,但是都不需要。
这将使您的awk脚本:
#!/bin/awk
### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.
# This block of code is executed for each line in the file
{
sum+=$2
# The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
# NR is a variable equal to the number of rows in the file
print "Average: " sum/ NR
# Change this to print the Average instead of just the number of rows
}
乔纳森·莱夫勒(Jonathan Leffler)的答案为awk提供了一个代表相同固定代码的衬线,另外还要检查至少有1行输入(这将停止除以零的错误)。如果
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句