最有效的方式来计算平均值 [英] the most efficient way to calculate average value
问题描述
我有一个文件,它看起来像:
I have a file, which looks like:
Lorem ipsum dolor sit amet... 2465m
id porttitor libero mauris at magna... 1m
istique pretium tincidunt. V...1200m
...
我要计算(使用UNIX命令时,awk,grep的等),尾随数之和,我的意思是(2465 + 1 + 1200 + ......)/ NUMBER_OF_LINES。什么是做到这一点的最好办法?
I want to calculate (using unix commands, awk, grep etc.) sum of trailing number, I mean (2465 + 1 + 1200 + ...) / NUMBER_OF_LINES. What is the best way to do that?
推荐答案
这使得它:
$ awk '{sum+=$NF+0} END{print "total sum is " sum " and average " sum/NR}' file
total sum is 3666 and average 1222
$ NF
表示每一行的最后一个字。它采用 $ NF + 0
让尾随 M
等字符不考虑。然后,它在保持之
变量的总和,即印在最后。
最后,按 NR
,其行数的加工值输出的平均值,取除以总和。
$NF
stands for the last word of every line. It uses $NF+0
so that the trailing m
and other characters are not taken into account. Then it keeps the sum in sum
variable, that is printed at the end.
Finally it prints the average, taken dividing the sum
by NR
, which has the value of number of lines processed.
这篇关于最有效的方式来计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!