October 8th, 2013

How to get averages from the command line using awk and NOT get the division by zero error

The simple way to get averages from the command line using awk is:

| awk '{a+=$1} END{print a/NR}'

But that will cause divsion by zero errors if nothing is returned, "awk: fatal: division by zero attempted."

So if you add a little code to it you can check to make sure it's greater than 0 first:

 | awk '{a+=$1} END{ if (NR > 0) {print a/NR} else {print NR}}' ;