最有效的方式来计算平均值

编程入门 行业动态 更新时间:2024-10-28 09:16:20
本文介绍了最有效的方式来计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个文件,它看起来像:

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.

更多推荐

最有效的方式来计算平均值

本文发布于:2023-10-20 08:48:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1510495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平均值   最有效   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!