bash 用于计算数据文件中一系列数字的平均值的脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15681498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scripts for computing the average of a list of numbers in a data file
提问by HymanWM
The file data.txt
contains the following:
该文件data.txt
包含以下内容:
1.00 1.23 54.4 213.2 3.4
The output of the scripts are supposed to be:
脚本的输出应该是:
ave: 54.646
Some simple scripts are preferred.
一些简单的脚本是首选。
回答by Chris Seymour
Here is one method:
这是一种方法:
$ awk '{s+=}END{print "ave:",s/NR}' RS=" " file
ave: 54.646
回答by nisetama
Another option is to use jq
:
另一种选择是使用jq
:
$ seq 100|jq -s add/length
50.5
-s
(--slurp
) creates an array for the input lines after parsing each line as JSON, or as a number in this case.
-s
( --slurp
) 在将每一行解析为 JSON 或在这种情况下解析为数字后,为输入行创建一个数组。
Or in the OP's case:
或者在 OP 的情况下:
tr \ \n<file|jq -s add/length|sed s/^/ave:\ /
回答by Vijay
perl -lane '$a+=$_ for(@F);print "ave: ".$a/scalar(@F)' file
if you have multiple lines and you just need a single average:
如果您有多条线并且只需要一个平均值:
perl -lane '$a+=$_ for(@F);$f+=scalar(@F);END{print "ave: ".$a/$f}' file