[英]using awk to average specified rows
我有一個像這樣的數據文件
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.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]}'
上一行的輸出(使用您的示例輸入)是:
average of a is 3.00
average of b is 4.00
average of c is 5.00
average of d is 5.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.