bash 如何计算 CSV 文件中一列的平均值?

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

How to compute the average of a column in a CSV file?

linuxbash

提问by John Threepwood

I would like to compute the average of a certain column in a CSV file with column separator ";". How can I do this with Linux command line tools such as awk?

我想用列分隔符“;”计算 CSV 文件中某一列的平均值。如何使用 awk 等 Linux 命令行工具执行此操作?

Example:

例子:

 foo;1;test
 bar;3;hello

Average of column 2is 2.

列的平均值22

回答by dimo414

A quick search for "bash average" turned up as the first result: Compute simple average using AWK

快速搜索“ bash average”作为第一个结果:Compute simple average using AWK

Tidied up for your use case, it's:

针对您的用例进行整理,它是:

$ awk -F';' '{sum+=; ++n} END { print "Avg: "sum"/"n"="sum/n }' < /tmp/yourdata
Avg: 4/2=2

回答by sergres

Lets think, you have csv file 1.csv. command should look like this:

让我们想想,你有 csv 文件 1.csv。命令应如下所示:

   cat 1.txt | awk -F';' '{sum+=} END {print sum/NR}'