Shell 使用awk对指定行求平均值
我有一个像这样的数据文件Shell 使用awk对指定行求平均值,shell,awk,Shell,Awk,我有一个像这样的数据文件 a 1 b 2 c 3 d 4 a 5 b 6 c 7 d 6 etc 我想输出到一个新文件 a average of 2nd column from all "a" rows b average of 2nd column from all "b" rows etc 其中a,b,c。。。还有数字。 我已经能够使用awk对第1列的特定值(下例中为1.4)执行此操作: awk '{ if ( $1 == 1.4) total
a 1
b 2
c 3
d 4
a 5
b 6
c 7
d 6
etc
我想输出到一个新文件
a average of 2nd column from all "a" rows
b average of 2nd column from all "b" rows
etc
其中a,b,c。。。还有数字。
我已经能够使用awk
对第1列的特定值(下例中为1.4)执行此操作:
awk '{ if ( $1 == 1.4) total += $2; count++ }
END {print total/10 }' data
虽然count
没有给我正确的行数(即,count应该是10,因为我在最后一行手动输入了10来进行平均)
我假设需要一个for循环,但我无法正确地实现它。
请帮忙。谢谢
awk '{a[$1]+=$2;c[$1]++}END{for(x in a)printf "average of %s is %.2f\n",x,a[x]/c[x]}'
上述行的输出(带有示例输入)为:
谢谢,这几乎是我想要的一切。但是,输出顺序不同(例如a、b、c、d…而是b、d、a、c)。不知道为什么会这样,但是否有一个快速修复方法可以像原始的那样进行排序?
awk
在排序方面不太好,所以只需在awk
命令|sort-k3
之后添加它即可。它将使用第3列对输出进行排序
average of a is 3.00
average of b is 4.00
average of c is 5.00
average of d is 5.00