I'm writing a bash script and I get this error:
bash: ((: ave=total/numLines : division by 0 (error token is "numLines ")
And this is my code:
total="$( cut -d '|' -f ${array[$index]} folder/${files[$x]} | awk '{ sum += $1 } END { print sum }' )"
numLines="$( cut -d '|' -f ${array[$index]} folder/${files[$x]} | awk 'NF' | wc -l )"
(( ave=total/numLines ))
The value of variable 'ave' could be calculated and printed correctly, but I keep getting the 'division by 0' error. I tried to assign a value to 'numLines' at the beginning but doesn't seem to work.
What's wrong and how can I fix it?
Building on @Barmar's and my comments:
AWK can extract fields with different delimiters (no need for cut
):
read -r total ave <<< "$(awk -F '|' -v field=${array[$index]} 'NF { sum += $field; count++ } END {print sum, sum/count}' "folder/${files[$x]}")"
Note that in sum += $field
, the dollar sign causes the field number held in the variable field
to refer to the contents of that field. (It's not a variable designation such as that used in Bash.) The -v
argument is the way to pass a Bash variable into AWK as an AWK variable. The pattern used here (NF
) matches all non-empty lines and the action is enclosed with {}
. The END
pattern is special and is executed when all input has been consumed.