9

I am calculating the average for a bunch of numbers in a bunch of text files like this:

grep '^num' file.$i | awk '{ sum += $2 } END { print sum / NR }'

But some times the file doesn't contain the pattern, in which cas I want the script to return zero. Any ideas of this slightly modified one-liner?

719016
  • 9,922
  • 20
  • 85
  • 158

3 Answers3

17

You're adding to your load (average) by spawning an extra process to do everything the first can do. Using 'grep' and 'awk' together is a red-flag. You would be better to write:

awk '/^num/ {n++;sum+=$2} END {print n?sum/n:0}' file
JRFerguson
  • 7,426
  • 2
  • 32
  • 36
5

Try this:

... END { print NR ? sum/NR : 0 }
mouviciel
  • 66,855
  • 13
  • 106
  • 140
2

Use awk's ternary operator, i.e. m ? m : n which means, if m has a value '?', use it, else ':' use this other value. Both n and m can be strings, numbers, or expressions that produce a value.

grep '^num' file.$i | awk '{ sum += $2 } END { print sum ? sum / NR : 0.0 }'
tripleee
  • 175,061
  • 34
  • 275
  • 318
shellter
  • 36,525
  • 7
  • 83
  • 90