Your Ad Here

Posted By

nickaubert on 01/05/11


Tagged

arithmetic


Versions (?)

Floating point average


 / Published in: Bash
 

All on one line for CLI convenience.

In this example, "file1" is assumed to contain a single column of floating point numbers. To get the average of the second column in a comma separated values file, change cat $FILE to cat $FILE | cut -d, -f 2

SCALE refers to the number of decimal places after the dot.

  1. FILE=file1 ; SCALE=2 ; SUM=0 ; COUNT=0; for i in $( cat $FILE ) ; do COUNT=$(( $COUNT + 1 )) ; SUM=$( echo "scale=$SCALE; $SUM + $i" | bc ) ; done ; AVG=$( echo "scale=$SCALE; $SUM / $COUNT" | bc ) ; echo $AVG

Report this snippet  

You need to login to post a comment.