lucineo
lucineo

Reputation: 13

Finding average with shell script

Let my input be lines of numbers, separated by spaces. Each line can have any number of numbers. There can be any number of lines. I have to find the average of all the numbers and display it up to 4 decimals.

For Example: Let the name of script file be avg.sh then

$ printf "1 2 3 4\n 5 6     7 8 9\n 10 -8" | ./avg.sh
4.2727

What I have done so far:

#! bin/sh
sum=0
for i in $*
do
sum=`expr $sum + $i`
done
avg=`expr $sum / $n`
echo Average=$avg

This is not working as I described. Any ideas?

Upvotes: 1

Views: 3821

Answers (3)

user8807135
user8807135

Reputation:

$(( )) can certainly do floating point, but you have to use 'typeset -F' to declare the variables:

    typeset -F avg sum
    sum=0
    while read buff           # reading the stdin
      do
        set -A nums ${buff}   # put stdin into indexed array
     done
    for ((i=0 ; i<${#nums[*]} ; i++))   # over the array elements
      do
        (( sum += ${nums[${i}]} ))
     done
    ((avg = sum/i))
    echo $i
    echo Average=$avg


            echo "1 2 3 4 5 6     7 8 9 10 -8" | ./foo
            Average=4.2727272727

Also, notice the gyrations to use stdin data to parameters (the array business)

Edited to add: @BenjaminW ksh Version AJM 93u+ 2012-08-01

Upvotes: -1

Benjamin W.
Benjamin W.

Reputation: 52556

You could use awk:

printf "1 2 3 4\n 5 6     7 8 9\n 10 -8" \
    | awk '{for (i=1;i<=NF;++i) {sum+=$i; ++n}} END {printf "%.4f\n", sum/n}'

This loops over all fields or each line, updating both sum and n, then prints the sum.

Upvotes: 2

anonymous
anonymous

Reputation: 386

sum=0
n=0
for i in $*
do
sum=`expr $sum + $i`
n=`expr $n + 1`
done
avg=`expr $sum / $n`
echo Average=$avg

Upvotes: 1

Related Questions