Sunday, June 10, 2007

Calcualting Average in UNIX Shell Script

I grabbed a piece of code to calculate an average for data in shell. It didn't work so I had to modify it. This is the result.


#!/bin/sh
n=0
sum=0
while read x
do
sum=`echo $sum + $x | bc`
if [ "$?" -eq "0" ]; then
n=`expr $n + 1`
fi
done
echo "scale=2;$sum/$n"| bc

3 comments:

  1. Other than removing the "-p" for read, and the comments, what does this fix that wasn't in the linked page?

    ReplyDelete
  2. changed sum=`expr $sum + $x` to sum=`echo $sum + $x | bc` so it can deal with large and floating point numbers. I added a comment about this in your blog a long time ago.

    ReplyDelete

[Due to much spam, comments are now moderated and will be posted after review]