bash- find average of numbers in line

前端 未结 4 1281
我寻月下人不归
我寻月下人不归 2021-01-22 01:54

I am trying to read a file line by line and find the average of the numbers in each line. I am getting the error: expr: non-numeric argument

I have narrowe

4条回答
  •  生来不讨喜
    2021-01-22 02:51

    With some minor corrections, your code runs well:

    while read -a rows
    do
        total=0
        sum=0
        for i in "${rows[@]}"
        do
            sum=`expr $sum + $i`
            total=`expr $total + 1`
        done
        average=`expr $sum / $total`
        echo $average
    done 

    With the sample input file, the output produced is:

    1
    5
    7
    5
    2
    5
    

    Note that the answers are what they are because expr only does integer arithmetic.

    Using sed to preprocess for expr

    The above code could be rewritten as:

    $ while read row; do expr '(' $(sed 's/  */ + /g' <<<"$row") ')' / $(wc -w<<<$row); done < filename
    1
    5
    7
    5
    2
    5
    

    Using bash's builtin arithmetic capability

    expr is archaic. In modern bash:

    while read -a rows
    do
        total=0
        sum=0
        for i in "${rows[@]}"
        do
            ((sum += $i))
            ((total++))
        done
        echo $((sum/total))
    done 

    Using awk for floating point math

    Because awk does floating point math, it can provide more accurate results:

    $ awk '{s=0; for (i=1;i<=NF;i++)s+=$i; print s/NF;}' filename
    1
    5.2
    7.4
    5.4
    2.8
    5.6
    

提交回复
热议问题