linux - 使用 Linux 在第 2 列中查找第 1 列中每个不同值的平均值

标签 linux shell awk

这是与我之前的帖子 Find the maximum values in 2nd column for each distinct values in 1st column using Linux 相关的问题

我有如下两列

ifile.dat
1   10
3   34
1   4
3   32
5   3
2   2
4   20
3   13
4   50
1   40
2   20

我要寻找的是在第 2 列中找到第 1 列中每个 1、2、3、4、5 的平均值。

ofile.dat
1   18    i.e. (10+4+40)/3 
2   11    i.e. (2+20)/2
3   26.33 i.e. (34+32+13)/3
4   35
5   3

虽然我知道一般命令,但我做不到。

最佳答案

使用 awk 你可以做:

awk '{a[$1]+=$2; c[$1]++} END{for (i in a) printf "%d%s%.2f\n", i, OFS, a[i]/c[i]}' file
1 18.00
2 11.00
3 26.33
4 35.00
5 3.00

关于linux - 使用 Linux 在第 2 列中查找第 1 列中每个不同值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31782292/

相关文章:

linux - 将特定行转为列

linux - 混帐 : reverts changes other than one specific files

shell - 用空格替换制表符以保持 n 空间对齐

ruby - 使用 SHA256 摘要签名的 OpenSSL RSA

linux - 用 sed 将旧链接 url 替换为新链接 url

python - 从多个文件中提取一列并将其粘贴到一个文件中

linux - 在 rc.local 之前启动时运行命令

linux - 为 linux 3.2.x 与基于 2.6.x 的系统编译的代码之间存在巨大的时间差异

linux - 如何将一个目录中文件的前300行复制到另一个目录?

bash - 在一列数字中,找到最接近某个目标值的值