对于另一列的每个唯一值,使用awk获取一列的最大值 [英] Using awk to get the maximum value of a column, for each unique value of another column

查看:116
本文介绍了对于另一列的每个唯一值,使用awk获取一列的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个文件,例如:

So I have a file such as:

10 1 abc
10 2 def
10 3 ghi
20 4 elm
20 5 nop
20 6 qrs
30 3 tuv

我想为第一列的每个值获取第二列的最大值,即:

I would like to get the maximum value of the second column for each value of the first column, i.e.:

10 3 ghi
20 6 qrs
30 3 tuv

如何使用awk或类似的unix命令?

How can I do using awk or similar unix commands?

推荐答案

您可以使用awk:

awk '$2>max[$1]{max[$1]=$2; row[$1]=$0} END{for (i in row) print row[i]}' file

输出:

10 3 ghi
20 6 qrs
30 3 tuv

说明:

awk命令使用关联数组max,其键为$1,值为$2.每次遇到已经存储在此关联数组max中的值时,我们都会更新上一个条目,并将整个行存储在具有相同键的另一个关联数组row中.最后,在END部分中,我们简单地遍历关联数组row并打印它.

awk command uses an associative array max with key as $1 and value as $2. Every time we encounter a value already stored in this associative array max, we update our previous entry and store whole row in another associative array row with the same key. Finally in END section we simply iterate over associative array row and print it.

这篇关于对于另一列的每个唯一值,使用awk获取一列的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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