递归grep只匹配模式的目录?
我试图找出如何通过只搜索子目录中与字符串匹配的文件来加速递归grep 例如:递归grep只匹配模式的目录?,grep,Grep,我试图找出如何通过只搜索子目录中与字符串匹配的文件来加速递归grep 例如: /foo/bar/baz/mylogs/somelog.log /foo/bar/notme.log /cat/dog/mylogs/anotherlog.log 我只需要grep*/mylogs/* 我可以找到以下所有日志文件 egrep -h -R --include \*.log '(pattherns|to|match)' 但这不 egrep -h -R --include \/mylogs/\*.log
/foo/bar/baz/mylogs/somelog.log
/foo/bar/notme.log
/cat/dog/mylogs/anotherlog.log
我只需要grep*/mylogs/*
我可以找到以下所有日志文件
egrep -h -R --include \*.log '(pattherns|to|match)'
但这不
egrep -h -R --include \/mylogs/\*.log '(pattherns|to|match)'
如何缩小include路径?一个选项是使用
find
查找与该名称匹配的任何目录,并使用其exec
标志对查找到的内容运行egrep
。下面的示例递归地通过模式“foo”的匹配目录执行egrps:
find . -type d -name mylogs -exec egrep -hR --include=\*.log foo {} +
+
后缀意味着find
将向单个egrep
进程提供尽可能多的结果。grep
有一个--exclude dir
选项,但没有--include dir
选项。--include
选项仅允许您匹配文件名,而不允许匹配文件路径
如果您正在使用较新版本的bash
shell或其他支持extglob
的shell,还可以执行以下操作:
$shopt-s extglob
$#无子目录的mylogs
$ls**/mylogs/*.log
cat/dog/mylogs/anotherlog.log foo/bar/baz/mylogs/somelog.log
$#如果mylogs也可以有子目录
$ls**/mylogs/**.log
a/b/mylogs/c/d/f.log cat/dog/mylogs/anotherlog.log foo/bar/baz/mylogs/somelog.log
一旦您满足文件匹配的需要,使用grep
和glob
grep-h'(pattherns | to | match)**/mylogs/*.log
永远不要使用任何GNU grep选项来查找文件,因为它们完全没有必要,只需使用大量的文件搜索选项和实际的g/re/p选项将您对grep的调用弄得一团糟。保持简单,在文件中使用find
查找文件和grep
查找g/re/p:
find . -type d -name mylogs -print0 |
xargs -0 -I XX find XX -maxdepth 1 -type f -name '*.log' -exec grep -h 'foo' {} +
或者,如果文件名不包含换行符,您甚至可以这样做:
find . -type f -name '*.log' | grep '/mylogs/' | xargs grep -h 'foo'
mylogs
中是否有子目录,是否也应该搜索它们?不,mylogs中没有子目录,只有以.log结尾的文件。您能解决这个问题吗?