Floating point average


/ Published in: Bash
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.