查找第2列的最大值为使用Linux第1列的每个不同的值 [英] Find the maximum values in 2nd column for each distinct values in 1st column using Linux

查看:428
本文介绍了查找第2列的最大值为使用Linux第1列的每个不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列如下:

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

我寻找什么是找到第1列第2列每个1,2,3,4,5的最大值。

What I look for is to find the maximum values in 2nd column for each 1,2,3,4,5 in 1st column.

ofile.dat
1   40 
2   20
3   34
4   50
5   3

我发现有人已经这样做了使用其他程序如<一href=\"http://stackoverflow.com/questions/30732798/get-the-maximum-values-of-column-b-per-each-distinct-value-of-column-a\">Get每列A的每个不同的值B柱

推荐答案

AWK 似乎是这个任务的主要候选人。简单地遍历输入文件,并保持通过所述第一列中的值和存储第2列的值,如果它比当前存储的值大索引的数组。在遍历迭代这个数组的末尾打印索引和相应的值

awk seems a prime candidate for this task. Simply traverse your input file and keep an array indexed by the first column values and storing a value of column 2 if it is larger than the currently stored value. At the end of the traversal iterate over the array to print indices and corresponding values

awk '{
    if (a[$1] < $2) {
        a[$1]=$2
    }
} END {
    for (i in a) {
        print i, a[i]
    }
}' ifile.dat

现在的结果将不会数值上的第一列进行排序,但如果所需应该是很容易可定影

Now the result will not be sorted numerically on the first column but that should be easily fixable if that is required

这篇关于查找第2列的最大值为使用Linux第1列的每个不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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