使用awk查找列的平均值

时间:2013-10-03 02:16:08

标签: bash 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

我觉得我很接近,但我真的不知道从哪里开始。代码不应该非常复杂,因为我们在课堂上看到的一切都是相当基础的。请告诉我。

4 个答案:

答案 0 :(得分:105)

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

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

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

如果你想使用shebang符号,你可以写:

#!/bin/awk

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

您还可以使用printf()和合适的格式(例如"%13.6e\n")来控制平均格式。

您还可以使用以下代码概括代码以平均第N列(此示例中为N=2):

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

答案 1 :(得分:8)

您的具体错误是第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
}

Jonathan Leffler的回答给出了awk one liner,它表示相同的固定代码,并且检查是否存在至少1行输入(这将停止任何除以零的错误)。如果

答案 2 :(得分:3)

试试这个:

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

NR是一个AWK内置变量来计算no。记录

答案 3 :(得分:1)

awk 's+=$2{print s/NR}' table | tail -1

我正在使用tail -1打印应该有平均数字的最后一行......