2013-10-03 265 views
38

我正在尝试使用awk来查找第二列数据的平均值。这是我当前的代码,我的导师提供的框架:使用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 

我想我接近,但我真的不知道在哪里从这里出发。如我们在课堂上所看到的一切已经相当基本的代码不应该是极其复杂的。请告诉我。

+1

我对awk没有太多,但这是否有帮助:http://stackoverflow.com/questions/8434000/awk-calculate-average-or-zero?rq=1 –

回答

84
awk '{ sum += $2; n++ } END { if (n > 0) print sum/n; }' 

添加数字在sum$2(第二列)(变量自动初始化通过awk为零),并增加行数(这也可以通过内置变量NR处理)。最后,如果至少读取了一个值,则打印平均值。

awk '{ sum += $2 } END { if (NR > 0) print sum/NR }' 

如果你想使用的家当符号,你可以写:

#!/bin/awk 

{ sum += $2 } 
END { if (NR > 0) print sum/NR } 

您也可以控制平均用printf()并以适当的格式的格式("%13.6e\n",例如)。

您也可以使用推广代码(此样品中N=2)以平均第N列:

awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum/NR }' 
1
awk 's+=$2{print s/NR}' table | tail -1 

我使用tail -1打印应有的平均数的最后一行。 ..

+2

一个非常奇怪的做法的东西。它有效,但我想不出使用这种技术的好理由。 –

4

你特定的错误是与线11:

awk 'BEGIN{sum+=$2}' 

这是一条线,其中awk被调用,并且它的BEGIN块被指定 - 但是你已经在awk脚本中,所以你不需要指定awk。你也想在输入的每一行运行sum+=$2,这样你就不是一个BEGIN块内想要它。因此,该行应仅仅是阅读:

sum+=$2 

你也不必行:

x=sum 
read name 

第一只创建一个同义词sum命名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 
} 

乔纳森·莱弗勒的回答给AWK一个衬垫代表相同的固定代码,增加检查至少有1线输入的(这将停止除以零误差)。如果

+0

这样做,非常感谢!我没有意识到,因为在awk脚本中,没有必要使用awk命令,菜鸟错误。再次感谢 –

+0

@BenZifkin如果你发现我的答案有用,你能接受答案吗? – imp25

3

试试这个:

ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}' 

NR是AWK内置变量来计算无。的记录

+0

欢迎使用堆栈溢出。如果您为几个月前的问题添加新的答案并且包含已接受的答案,那么您的新答案需要提供一些独特的新信息。目前尚不清楚这是否能完成这项工作。为什么你把'ls -l'输入'awk'并不明显?也不清楚你为什么使用':'作为字段分隔符。问题表明它需要总结第2列,所以不清楚为什么总结第5列。 –

+0

如何同时打印文件名? –