使用awk查找列的平均值

Ben*_*kin 48 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
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

awk: avg.awk:11:        awk 'BEGIN{sum+=$2}' $name
awk: avg.awk:11:            ^ invalid char ''' in expression
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*ler 111

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'
Run Code Online (Sandbox Code Playgroud)

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

awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'
Run Code Online (Sandbox Code Playgroud)

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

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }
Run Code Online (Sandbox Code Playgroud)

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

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

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


imp*_*p25 9

您的具体错误是第11行:

awk 'BEGIN{sum+=$2}'
Run Code Online (Sandbox Code Playgroud)

这是一个awk调用的行,并且BEGIN指定了它的块 - 但是您已经在awk脚本中,因此您不需要指定awk.您还希望sum+=$2在每行输入上运行,因此您不希望它在一个BEGIN块中.因此该行应该简单地读取:

sum+=$2
Run Code Online (Sandbox Code Playgroud)

你也不需要这些线:

x=sum
read name
Run Code Online (Sandbox Code Playgroud)

第一个只是创建了一个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
}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

尝试这个:

ls -l  | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
Run Code Online (Sandbox Code Playgroud)

NR 是一个 AWK 内置变量,用于计算编号。记录数