What's the quickest way to get the mean of a set of numbers from the command line?

和自甴很熟 提交于 2019-12-05 01:37:25

Awk

awk '{total += $1; count++ } END {print total/count}'
awk ' { n += $1 }; END { print n / NR }'

This accumulates the sum in n, then divides by the number of items (NR = Number of Records).

Works for integers or reals.

Using Num-Utils for UNIX:

average 1 2 3 4 5 6 7 8 9
perl -e 'while (<>) { $sum += $_; $count++ } print $sum / $count, "\n"';

In Powershell, it would be

get-content .\meanNumbers.txt | measure-object -average

Of course, that's the verbose syntax. If you typed it using aliases,

gc .\meanNumbers.txt | measure-object -a

Using "st" (https://github.com/nferraz/st):

$ st numbers.txt
N      min   max    sum    mean  sd
10.00  1.00  10.00  55.00  5.50  3.03

Specify an option to see individual stats:

$ st numbers.txt --mean
5.5

(DISCLAIMER: I wrote this tool :))

Perl.

@a = <STDIN>;

for($i = 0; $i < #@a; $i++)
{
   $sum += $a[i];
}

print $a[i]/#@a;

Caveat Emptor: My syntax may be a little whiffly.

Ruby one liner

cat numbers.txt | ruby -ne 'BEGIN{$sum=0}; $sum=$sum+$_.to_f; END{puts $sum/$.}'

source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!