bash awk 计算平均值或零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8434000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:09:42  来源:igfitidea点击:

awk calculate average or zero

bashawk

提问by 719016

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

我正在计算一堆文本文件中一堆数字的平均值,如下所示:

grep '^num' file.$i | awk '{ sum +=  } 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?

但有时文件不包含模式,其中 cas 我希望脚本返回零。这个稍微修改的单线有什么想法吗?

回答by JRFerguson

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:

您通过生成一个额外的进程来完成第一个可以做的所有事情,从而增加了您的负载(平均)。一起使用 'grep' 和 'awk' 是一个危险信号。你最好这样写:

awk '/^num/ {n++;sum+=} END {print n?sum/n:0}' file

回答by mouviciel

Try this:

尝试这个:

... END { print NR ? sum/NR : 0 }

回答by shellter

Use awk's ternary operator, i.e. m ? m : nwhich 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.

使用 awk 的三元运算符,也就是说m ? m : n,如果 m 有一个值 '?',就使用它,否则 ':' 使用另一个值。n 和 m 都可以是字符串、数字或产生值的表达式。

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