使用 grep 排除嵌套目录

Jak*_*ake 6 grep

我想从我的 grep 搜索中排除嵌套目录,例如/path/to/file. 例如:

jake@jake-laptop:~/test$ egrep -r --exclude-dir="path" "hello" .
jake@jake-laptop:~/test$ egrep -r --exclude-dir="to" "hello" .
jake@jake-laptop:~/test$ egrep -r --exclude-dir="file" "hello" .
jake@jake-laptop:~/test$ egrep -r --exclude-dir="path/to/file" "hello" .
./path/to/file/f.txt:hello
Run Code Online (Sandbox Code Playgroud)

在最后一行中,文件没有被排除,显然是因为我有多个嵌套目录提供了exclude-dir参数。如何获得最后一个示例以排除path/to/file目录中的搜索?

meu*_*euh 5

似乎--exclude-dir仅与路径的基本名称(即当前子目录)进行比较。因此 path/to/file 永远不会匹配 dir "file",但只会--exclude-dir=file匹配,或者 glob 版本,例如--exclude-dir=*ile.

通常的替代方法是使用find,例如,如果它处理选项-path

find . -path ./path/to/file -prune -o -type f -exec egrep -l 'hello' {} +
Run Code Online (Sandbox Code Playgroud)

之后的模式-path必须与包括起始目录在内的路径匹配,但您可以使用 glob 来简化,例如'*path*file*',其中 * 也匹配 / 。

否则,您可以求助于find | sed | xargs egrep.