首页 > 解决方案 > grep 文件列表中的最后一个匹配项

问题描述

我在同一个文件夹下有很多文件:

uut01_010203030.txt
uut02_020038300.txt
uut03_202002003.txt

我可以单独 grep 最后一次出现:

tac uut01_*.txt | grep -m 1 'some_pattern'

我可以将文件提供给 grep 文件中第一次出现的模式:

ls uut*.txt | xargs grep -m 1 'some_pattern'

但是,我不能真正将 tac 和 grep 结合在一起,以下命令给了我错误:

ls uut*.txt | xargs tac | grep -m 1 'some_pattern'
xargs: tac: terminated by signal 13

我能做些什么来解决这个问题?

标签: bashgrepxargs

解决方案


$ tail -n +1 file*
==> file1 <==
1
2
3

==> file2 <==
1
2
3
4
5

==> file3 <==
1
2
3
4

$ grep -H '.' file* | tac | awk -F':' '!seen[$1]++'
file3:4
file2:5
file1:3

$ awk '/./{hits[FILENAME]=$0} END{for (f in hits) print f, hits[f]}' file*
file1 3
file2 5
file3 4

推荐阅读