How to add lines of a file and average them

I'm reading in numbers from a file and trying to add them together. Here is the code so far. I know the 1+2+3.... part is wrong. The file has five numbers in it with each number on its own line. The numbers are decimals if that matters. Thanks.

while read EachLine
do
  echo $EachLine
done < myfilename
  echo sum=$(( "1 + 2 + 3 + 4 + 5" ))
fi

If by "the numbers are decimals" you mean they are real numbers (1.234) and not integers (1), and you are using ksh, then you can do it right in the shell:

#!/usr/bin/env ksh
# this won't work in bash
sum=0.0
n=0
while read value
do
   sum=$(( sum + value ))
   n=$(( n + 1 ))
done <input-file-name

echo "$n values summed to $sum with an average of $(( sum/$n.0 ))"

---------- Post updated at 22:52 ---------- Previous update was at 22:48 ----------

If ksh isn't an option, you could use awk:

awk '{ sum += $1; } END {printf( "%d values summed to %.2f with an average of %.4f\n", NR, sum, sum/NR ); }'  input-file

Thanks for the reply. I'd like to keep them in a file and not in the shell though. Is there a way to do that?

They'd be in a file. The script, or the awk, read's the file, sums the numbers and presents the average. The 'input-file' or 'input-file-name' in the samples would be the name of your file that contains the numbers.

1 Like

You're right. Sorry, I had a brain cramp. I've tried both ways since I'm using ksh. I lose the decimal places using the ksh method, but not with the awk.

ksh88 does not have floating point arithmetic, ksh93 does..

1 Like

I got it worked out using bc. Thanks for the help.