arrays - bash- find average of numbers in line -
i trying read file line line , find average of numbers in each line.  getting error: expr: non-numeric argument
i have narrowed problem down sum=expr $sum + $i, i'm not sure why code doesn't work.
while read -a rows     in "${rows[@]}"             sum=`expr $sum + $i`         total=`expr $total + 1`     done     average=`expr $sum / $total` done < $filename   the file looks (the numbers separated tabs):
1       1       1       1       1 9       3       4       5       5 6       7       8       9       7 3       6       8       9       1 3       4       2       1       4 6       4       4       7       7      
with minor corrections, code runs well:
while read -a rows     total=0     sum=0     in "${rows[@]}"             sum=`expr $sum + $i`         total=`expr $total + 1`     done     average=`expr $sum / $total`     echo $average done <filename   with sample input file, output produced is:
1 5 7 5 2 5   note answers because expr integer arithmetic.
using sed preprocess expr
the above code rewritten as:
$ while read row; expr '(' $(sed 's/  */ + /g' <<<"$row") ')' / $(wc -w<<<$row); done < filename 1 5 7 5 2 5   using bash's builtin arithmetic capability
expr archaic.  in modern bash:
while read -a rows     total=0     sum=0     in "${rows[@]}"             ((sum += $i))         ((total++))     done     echo $((sum/total)) done <filename   using awk floating point math
because awk floating point math, can provide more accurate results:
$ awk '{s=0; (i=1;i<=nf;i++)s+=$i; print s/nf;}' filename 1 5.2 7.4 5.4 2.8 5.6      
Comments
Post a Comment