bash AWK 将列的总和除以文件中的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10180189/
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 02:02:34  来源:igfitidea点击:

AWK divide sum of column by number of lines in file

linuxbashunixawk

提问by general exception

I have a file which contains lines of data like below

我有一个包含如下数据行的文件

300,,,292,15.4,0,04/16/12 20:10:39
200,,,292,15.4,0,04/16/12 20:10:39
100,,,292,15.4,0,04/16/12 20:10:39

Using awk i am summing up the first column like this

使用 awk 我总结了这样的第一列

awk -F ',' '{ x = x +  } END { print x }' MyFile

Which is retuning 600 no problems.

这是重新调整600没有问题。

I want to modify this command to also calculate the amount of lines in the file and then instead of { print x }i want to { print x / y }where y is the number of lines in the file.

我想修改这个命令来计算文件中的行数,然后{ print x }我想而不是我想要{ print x / y }y 是文件中的行数。

So it would return 600 / 3 = 200.

所以它会返回 600 / 3 = 200。

回答by Jonathan Leffler

The number of records processed so far is in NR:

到目前为止处理的记录数在 NR 中:

awk -F, '{ x +=  } END { print x " " x/NR }' MyFile

NR counts across all files processed; here, that's a single file. There's also FNR in at least some versions of awk; that counts the number of records processed in the current file. In this example, NR == FNR at all times because there's a single file.

处理的所有文件的 NR 计数;在这里,这是一个文件。至少在某些版本中也有 FNR awk;计算当前文件中处理的记录数。在此示例中,NR == FNR 始终是因为只有一个文件。

回答by gpojd

Did you try NR for the number of records?

您是否尝试过 NR的记录数

awk -F ',' '{ x = x +  } END { print x/NR }' MyFile