按bash中的“最后"值分组 [英] group by 'last' value in bash

查看:71
本文介绍了按bash中的“最后"值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两列的文件:

1,112
1,123
2,123
2,124
2,144
3,158
4,123
4,158
5,123

我需要知道每个column1的最后column2值:

I need to know last column2 value for each column1:

1,123
2,144
3,158
4,158
5,123

如何在bash中执行此操作?

推荐答案

解决方案对:

1)使用tac反转输入文件,然后使用sort

1) With tac to reverse input file and sort

$ tac ip.txt | sort -u -t, -k1,1n
1,123
2,144
3,158
4,158
5,123

2)使用perl

$ perl -F, -ne '$h{$F[0]} = $_; END{print $h{$_} foreach (sort {$a <=> $b} keys %h)}' ip.txt 
1,123
2,144
3,158
4,158
5,123

,上分割的输入行,并且hash变量会根据第一个字段进行更新,如果第一个字段匹配,则有效地丢弃了前几行.最后,根据已排序的键打印哈希变量

Input lines split on , and hash variable keeps updating based on first field, effectively throwing away previous lines if first field matches. At end, the hash variable is printed based on sorted keys

感谢@choroba指出在两种情况下都需要数字排序

Thanks @choroba for pointing out that numeric sort is needed in both cases

这篇关于按bash中的“最后"值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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