我需要搜索目录及其子目录中每个文件的前 50 行。
这将完成递归部分,但如何限制每个文件的前 50 行?
grep -r "matching string here" .
Run Code Online (Sandbox Code Playgroud)
其中一些文件很大,我只希望它们在前 50 行中匹配。我试图通过不在某些文件中搜索兆字节的二进制数据来加快该过程。
gni*_*urf 11
如果您只想要匹配的文件:
find . -type f -exec bash -c 'grep -q "matching string here" < <(head -n 50 "$1")' _ {} \; -printf '%p\n'
Run Code Online (Sandbox Code Playgroud)
或者
find . -type f -exec bash -c 'grep -q "matching string here" < <(head -n 50 "$1") && printf '%s\n' "$1"' _ {} \;
Run Code Online (Sandbox Code Playgroud)如果您只想要匹配的字符串:
find . -type f -exec head -n 50 {} \; | grep "matching string here"
Run Code Online (Sandbox Code Playgroud)
或更好,
find . -type f -exec head -q -n 50 {} + | grep "matching string here"
Run Code Online (Sandbox Code Playgroud)如果你同时想要:
find . -type f -exec bash -c 'mapfile -t a < <(head -n 50 "$1" | grep "matching string here"); printf "$1: %s\n" "${a[@]}"' _ {} \;
Run Code Online (Sandbox Code Playgroud)评论。
sed而不是组合head--可能会稍微容易一些grep。-exec ... +在每种方法中使用,但是您必须自己编写内部循环代码!(留给读者的琐碎练习)。如果您有大量文件,这可能会稍微高效一些。| 归档时间: |
|
| 查看次数: |
8295 次 |
| 最近记录: |