Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk calculate average or zero

Tags:

bash

awk

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?

like image 201
719016 Avatar asked Dec 08 '11 16:12

719016


2 Answers

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
like image 106
JRFerguson Avatar answered Sep 23 '22 22:09

JRFerguson


Try this:

... END { print NR ? sum/NR : 0 }
like image 43
mouviciel Avatar answered Sep 22 '22 22:09

mouviciel