AWK计算平均或零 [英] awk calculate average or zero

查看:182
本文介绍了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?

推荐答案

您要添加到您的负载(平均)通过产生一个额外的过程中做的一切的第一个可以做到的。使用'grep的'和'的awk'一起是一个红色的标志。你会更好地写:

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

这篇关于AWK计算平均或零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆