Using any tools which you would expect to find on a nix system (in fact, if you want, msdos is also fine too), what is the easiest/fastest way to calculate the mean of a set of numbers, assuming you have them one per line in a stream or file?
Asked
Active
Viewed 2,015 times
8 Answers
17
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.

Adam Liss
- 47,594
- 12
- 108
- 150
-
Nice on the NR trick, wasn't sure which awk answer to accept so I copped out and went for the one with the most votes! – Anthony Oct 18 '08 at 22:00
5
Using Num-Utils for UNIX:
average 1 2 3 4 5 6 7 8 9

Mitch Wheat
- 295,962
- 43
- 465
- 541
-
Interesting. I installed this on Ubuntu and I had to specify the numbers on stdin, not as arguments. – Glyph Oct 18 '08 at 03:28
3
perl -e 'while (<>) { $sum += $_; $count++ } print $sum / $count, "\n"';

Robert Gamble
- 106,424
- 25
- 145
- 137
2
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 :))

user2747481
- 611
- 5
- 4
1
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

Knox
- 2,909
- 11
- 37
- 65
0
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.

Paul Nathan
- 39,638
- 28
- 112
- 212
0
Ruby one liner
cat numbers.txt | ruby -ne 'BEGIN{$sum=0}; $sum=$sum+$_.to_f; END{puts $sum/$.}'

american-ninja-warrior
- 7,397
- 11
- 46
- 80