bash- find average of numbers in line

前端 未结 4 1328
我寻月下人不归
我寻月下人不归 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:48

    This is a pretty old post, but came up at the top my Google search, so thought I'd share what I came up with:

    while read line; do
        # Convert each line to an array
        ARR=( $line )
    
        # Append each value in the array with a '+' and calculate the sum
        #   (this causes the last value to have a trailing '+', so it is added to '0')
        ARR_SUM=$( echo "${ARR[@]/%/+} 0" | bc -l)
    
        # Divide the sum by the total number of elements in the array
        echo "$(( ${ARR_SUM} / ${#ARR[@]} ))"
    done < "$filename"
    

提交回复
热议问题