小编典典

如何从grep -R中排除目录?

linux

我想遍历除“ node_modules”目录以外的所有子目录。


阅读 1073

收藏
2020-06-02

共1个答案

小编典典

解决方案1(组合findgrep

该解决方案的目的不是要处理grep性能,而是要显示一个可移植的解决方案:还应该与busybox或2.5之前的GNU版本一起使用。

使用 find ,排除foo和bar目录:

find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print

然后结合 find 使用和 grep 作为递归解决方案的非递归使用:

find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;

解决方案2(递归使用grep):

您已经知道此解决方案,但是我添加了它,因为它是最新,最有效的解决方案。请注意,这是一种不易移植的解决方案,但更易于理解。

grep -R --exclude-dir=node_modules 'some pattern' /path/to/search

要排除多个目录,请--exclude-dir用作:

--exclude-dir={node_modules,dir1,dir2,dir3}

解决方案3(Ag)

如果您经常搜索代码,Ag(银搜索器)是grep的一种更快的选择,它是为搜索代码而定制的。例如,它会自动忽略中列出的文件和目录.gitignore,因此您不必继续将相同的繁琐的排除选项传递给grepfind

2020-06-02