【问题标题】:grep last match from a list of filesgrep 文件列表中的最后一个匹配项
【发布时间】:2019-07-16 00:48:14
【问题描述】:

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

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

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

【问题讨论】:

  • 你想达到什么目的?
  • 这么多选择....for file in uut*.txt; do ...ls uut*.txt | xargs -L 1 sh -c 'tac "$0" | grep ...' 怎么样

标签: bash grep xargs


【解决方案1】:
$ 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

【讨论】:

    【解决方案2】:

    是的,我喜欢以下命令效果很好:

    for f in $(find . -name "uut*"); do tac $f | grep -m 1 'some_pattern'; done
    

    【讨论】:

    • 确认!不要那样做。而是使用 -exec 并执行类似 find . -name 'uut*' -exec sh -c 'grep "foo" $1 | sed -n "\$p"' _ {} \; 的操作
    • 使用-exec的原因是什么?为什么使用 for 循环不好?
    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多