【发布时间】:2017-05-28 11:02:05
【问题描述】:
我想统计当前目录有多少文件在最后一行有字符串"A"。
第一个解决方案:tail -n 1 * | grep \"A\"| wc -l
这很好用,但是当有更多文件时它会bash: /usr/bin/tail: Argument list too long。
有没有办法绕过它?
如果我还可以选择获取 哪些 文件包含它,则可以加分。
编辑:我的文件夹包含 343729 个文件
EDIT2:@tso 在他的评论中有用地指出了文章I'm getting "Argument list too long". How can I process a large list in chunks?。
结果:
@tso 解决方案for f in $(find . -type f); do tail -1 $f|grep \"A\"; done|wc -l 大约需要 20 分钟
@lars 解决方案grep -P "\"A\"*\Z" -r . | wc -l 大约需要 20 分钟
@mklement0 解决方案printf '%s\0' * | xargs -0 sh -c 'tail -q -n 1 "$@" | grep \"A\"' - | wc -l 大约需要 10 分钟
@james 解决方案(在 cmets 中)for i in * ; do awk 'END{if(/a/)print FILENAME}' "$i" ; done 大约需要 25 分钟
@codeforester find . -type f -exec tail -n 1 -- {} + | grep -EB 1 '^[^=]+A' | grep -c '^==>' 需要超过 20 分钟。
@mklement0 和@codeforester 解决方案还有一个优点,如果我想更改 grep 模式,我第二次运行它需要零时间,我猜这是由于某种缓存。
我已经接受了@mklement0 的答案似乎是最快的,但我仍然想提及@tso 和@lars 的贡献,并且根据我的个人知识,这是一个更简单且适应性强的解决方案。
【问题讨论】: