Ubuntu – How to compute the mean from ASCII file data in bash

bashcommand line

In bash I can grep some time measurements from a log file like this

grep "time:" myLogfile.txt | cut -d' ' -f 3 >> timeMeasurements.txt

#timeMeasurements.txt
2.5
3.5
2.0
...

Now I would like to compute the mean value from the values in timeMeasurements.txt. What is the quickest way to do that in bash?
I know that there is gnuplot and R but it seems like one has to write some lengthy script for either one on them.

Best Answer

Another way, using sed and bc:

sed 's/^/n+=1;x+=/;$ascale=1;x/n' timemeasurements.txt | bc

The sed expression converts the input to something like this:

n+=1;x+=2.5
n+=1;x+=3.5
n+=1;x+=2.0
scale=1;x/n

This is piped to bc which evaluates it line-by-line.

Related Question