Groupwise uniq 命令?

mik*_*iku 7 awk text-processing group uniq

我正在搜索从以下格式的文件中获取的命令:

hello 32
hello 67
hi    2
ho    1212
ho    1390
ho    3000
Run Code Online (Sandbox Code Playgroud)

对于这种格式(通过获取“组”的最后一行进行重复数据删除):

hello 67
hi    2
ho    3000
Run Code Online (Sandbox Code Playgroud)

目前我正在使用 Python 和 Pandas 代码段:

    df = pd.read_csv(self.input().path, sep='\t', names=('id', 'val'))

    # how to replace this logic with shell commands?
    surface = df.drop_duplicates(cols=('id'), take_last=True)

    with self.output().open('w') as output:
        surface.to_csv(output, sep='\t', cols=('id', 'val'))
Run Code Online (Sandbox Code Playgroud)

更新:感谢您的精彩回答。以下是一些基准:

输入文件为 246M,包含 8583313 行。顺序无关紧要。第一列的固定大小为 9 个字符。

输入文件示例:

000000027       20131017023259.0        00
000000027       20131017023259.0        11
000000035       20130827104320.0        01
000000035       20130827104320.0        04
000000043       20120127083412.0        01
...
Run Code Online (Sandbox Code Playgroud)
                              time        space complexity

tac .. | sort -k1,1 -u        27.43682s   O(log(n))
Python/Pandas                 11.76063s   O(n)
awk '{c[$1]=$0;} END{for(...  11.72060s   O(n)
Run Code Online (Sandbox Code Playgroud)

由于第一列有固定长度,uniq -w也可以使用:

tac {input} | uniq -w 9        3.25484s   O(1)
Run Code Online (Sandbox Code Playgroud)

Mik*_*kel 5

这看起来很疯狂,希望有更好的方法,但是:

tac foo | sort -k 1,1 -u
Run Code Online (Sandbox Code Playgroud)

tac 用于反转文件,因此您将获得最后一个而不是第一个。

-k 1,1 说只使用第一个字段进行比较。

-u 使它独一无二。