0

I am writing a shell script to calculate the averages of numbers from a file but for some reason bash is not adding my numbers together.

I have tried multple ways of formatting the sum='expr $sum + $num' but keep getting errors.

while read line
do  
    sum=0
    count=0
    average=0
    median=0

    #read each line, sort it and put it into tempRows file
    echo "$line" >> $tempRow
    sort $tempRow

    #add each number to the sum for avg calculation
    for i in $tempRow
        do
        num=$i
        count=`expr $count + 1`
        echo "count: $count"
        sum=`expr $sum + $num`
        echo "sum: $sum"    
        done

    #perform and print average calc at the end of each line
    average=`expr $sum / $count`

    echo -e "$average\t"

    rm -f $tempRow
done < $tempFile

Currently this code gives me following output before quitting

count: 1
expr:non-numeric argument
sum:
expr:syntax error

I am sorting each line before adding to tempRow for a later median calculation A sample file would contain multiple rows and columns of whole numbers and I would print out each rows average and median

3

Run bash -x myscript. That'll give you a trace of the execution which should make the problems clear.

Your main problem is

for i in $tempRow

The variable $tempRow contains a file name. Assuming that the name of the file does not contain any whitespace or wildcard characters, $tempRow expands to a list of one word which is that file name. So the for loop body runs once, with i set to the name of the file.

It appears that you wanted to iterate over the lines of the file. Use while read for that. Or rather, while IFS= read -r i; do ….

Some additional tips:

0

You should provide a little more info, like the contents of the file that $tempFile points to. Then I'd be able to help more.

cat $tempFile|while read line
do  
  sum=0
  count=0
  average=0
  median=0

  #read each line, sort it and put it into tempRows file
  echo "$line" >> $tempRow
  sort $tempRow

  #add each number to the sum for avg calculation
  for i in $(cat $tempRow)
  do
    count+=1
    echo "count: $count"
    sum+=$i
    echo "sum: $sum"    
  done

  #perform and print average calc at the end of each line
  average=$((sum / count))

  echo "$average"

  rm -f $tempRow
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.