Agnus Dei (jackal) wrote,
Agnus Dei
jackal

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}}' ;
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

  • 0 comments