使用awk查找列的平均值

我是Zifkin

我正在尝试查找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

我想我已经很近了,但是我真的不知道从这里去哪里。该代码不应太复杂,因为我们在课堂上看到的一切都是相当基本的。请告诉我。

imp25

您的特定错误与第11行有关:

awk 'BEGIN{sum+=$2}'

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

sum+=$2

您也不需要以下行:

x=sum
read name

第一个只是创建了sumnamed的同义词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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

查找连续列的平均值

来自分类Dev

使用JS查找数组的平均值

来自分类Dev

使用mysql查找平均值

来自分类Dev

使用必须查找平均值

来自分类Dev

查询以使用每个平均值的计数查找存储在mongodb中的平均值的平均值

来自分类Dev

查找特定列的平均值,并保留所有具有特定平均值的行

来自分类Dev

如何使用熊猫中的公共列查找多列的平均值

来自分类Dev

使用Python查找分散数据集的平均值(或滚动平均值)

来自分类Dev

每列n个数据的awk平均值

来自分类Dev

每列n个数据的awk平均值

来自分类Dev

Python如何使用数据框应用方法查找列的平均值

来自分类Dev

SQL-如何仅使用最后N行中的值查找列的平均值

来自分类Dev

大熊猫:查找所选列的平均值

来自分类Dev

从字典值的嵌套列表中查找列的平均值

来自分类Dev

如何在SAS中查找列的平均值

来自分类Dev

VBA:查找具有动态范围的列的平均值

来自分类Dev

查找列中最后 10 个数值的平均值

来自分类Dev

使用AWK进行的前N次比赛的平均值

来自分类Dev

使用大熊猫查找每日平均值

来自分类Dev

使用Python的Pandas按箱查找平均值

来自分类Dev

使用递归查找整数数组的平均值

来自分类Dev

在python中使用熊猫查找年度平均值

来自分类Dev

使用递归查找整数数组的平均值

来自分类Dev

在mysql中使用group by子句查找平均值

来自分类Dev

使用 map 查找嵌套列表的平均值

来自分类Dev

列对的矩阵平均值

来自分类Dev

多列平均值

来自分类Dev

尝试使用 for 循环查找调和平均值、地理平均值、总和、产品、平均值时退出错误

来自分类Dev

在R中按月查找列的平均值/均值时出错

Related 相关文章

热门标签

归档