简体   繁体   English

使用awk计算行的平均值

[英]Calculate avg of a row using awk

I have been working a script that calculates avg of a rows by reading input from a txt file 我一直在编写一个脚本,通过读取txt文件的输入来计算行的平均值

sample text input file input.txt 示例文本输入文件input.txt

157361 155687 156158 156830
149610 151824 152353 152027
159195 158490 159030 159243
153222 154227 154578 154390
168761 170078 170044 170107
147166 146477 146735 147678
155745 152142 155141 154140
148860 150040 149223 148246
147239 149693 148144 147990
148045 147987 149466 149535
146945 146206 145681 145852
156559 155188 156274 154962
143169 143798 142753 144045
153814 153320 153732 156621

I'm working on the below awk command: 我正在研究下面的awk命令:

awk '{sum=0; for(i=0; i<=NF; i++){sum+=$i}; sum/=NF; print sum}' input.txt

i'm getting 156679 as expected result for row1 avg:"somewhere its reading blank space as variable) with the above awk expression. 我正在获得156679作为row1 avg的预期结果:“某处其读取空白区域为变量”,具有上述awk表达式。

cal row1 excpected avg would be :(157361+155687+156158+156830)/4 = 156509

Im not getting expected output the avg am geting is wrong expected avg's for the above input file 我没有得到预期的输出avg am geting是错误的预期avg的上述输入文件

row1 expected avg :156509
row2 expected avg :151454

Field numbers in AWK start from 1 and not from 0 . AWK中的字段编号从1开始,而不是从0 So, in your for loop you need to put i = 1 所以,在你的for循环中你需要把i = 1

Doing: 这样做:

awk '{sum = 0; for (i = 1; i <= NF; i++) sum += $i; sum /= NF; print sum}' input.txt

I obtained the right results: 我得到了正确的结果:

156509
151454
158990
154104
169748
147014
154292
149092
148266
148758
146171
155746
143441
154372

另一种实现此目标的简短方法:

$ sed 's/ /+/g;s/.*/(&)\/4/g' file.txt | bc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM