Unix bash:根据另一列的值选择一列中具有唯一值的行 [英] Unix bash: select rows with unique value in one column, based on value of another column

查看:45
本文介绍了Unix bash:根据另一列的值选择一列中具有唯一值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的文件,看起来像这样:

I have a file with two columns that looks something like this:

1 3
1 4
2 3
3 3
4 3
4 4

我想把它变成一个在第一列中具有唯一值的文件,并且重复的行只保留第二列中具有最大值的行,所以新文件看起来像这样:

I want to make this into a file with unique values in the first columns, and of the duplicate rows only keep the rows with the largest values in the second column, so the new file looks like this:

1 4
2 3
3 3
4 4

关于如何使用 bash/awk/etc 实现这一目标的任何想法?

Any ideas on how to achieve this using bash/awk/etc?

推荐答案

使用 awk,您可以使用关联数组来管理此问题,该数组的键为第 1 列,值为第 2 列的最大值:

Using awk you can manage this using an associative array that has key as column-1 and value as maximum of column-2:

awk '$2 > a[$1]{a[$1] = $2} END{for (i in a) print i, a[i]}' file

1 4
2 3
3 3
4 4

这篇关于Unix bash:根据另一列的值选择一列中具有唯一值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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