AishwaryaKulkarni
AishwaryaKulkarni

Reputation: 784

Division by zero values in awk

I am calculating an average score as follows:

average_score=$(awk "BEGIN {printf \"%.2f\",${sum_of_score}/${number_of_lines}}")

where sum_of_scores is calculated as follows for each greped ID:

sum_of_score=$(grep 271712:E1 M10.6.txt | awk '{s+=$5} END {print s}')

number_of_lines=$(grep 271712:E1 M10.6.txt | awk 'END{print FNR}')

However at times the value of sum_of_score and /or number_of_lines might be zero and hence I am getting an error:

awk: BEGIN {printf "%.2f",/0}
awk:                       ^ unterminated regexp
awk: cmd. line:1: BEGIN {printf "%.2f",/0}
awk: cmd. line:1:                         ^ unexpected newline or end of string

How can I handle this error?

Upvotes: 0

Views: 733

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74596

Your sum_of_score variable should be computed like this:

sum_of_score=$(awk '/271712:E1/ { sum += $5 } END { print sum + 0 }')

The + 0 means that sum is evaluated in a numeric context, so an empty sum is 0 rather than an empty string.

If you just want the average (the mean), then do this:

awk '/271712:E1/ { sum += $5; ++count } END { if (count) print sum / count }'

The if (count) prevents a division by 0 if count hasn't been incremented.

Your "division by zero" errors aren't really anything to do with dividing by zero; they're syntax errors. The messages in each error describes what's wrong!

Upvotes: 5

Related Questions