awk calculate average or zero

前端 未结 3 461
甜味超标
甜味超标 2020-12-09 21:47

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 }\'
         


        
3条回答
  •  天命终不由人
    2020-12-09 22:09

    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
    

提交回复
热议问题