我如何从grep -R中排除目录? [英] How can I exclude directories from grep -R?
问题描述
我想遍历所有的子目录,除了node_modules目录外。 解决方案1(combine find
和 grep
)
这个解决方案并不是要处理 grep
性能,而是展示一个可移植的解决方案:还应该使用busybox或2.5以前的GNU版本。
使用 find
,排除foo和bar目录: pre> 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 -Hnyour text to find{} 2> / dev / null \;
解决方案2(递归使用 grep $ c $你已经知道这个解决方案了,但是我增加了它,因为它是最新的和有效的解决方案。注意,这是一个不太便于使用的解决方案,但更易于理解。
grep -R --exclude-dir = node_modules'some pattern '/ path / to / search
解决方案3(Ag) p>
如果您经常搜索代码,那么 Ag(The Silver Searcher)是grep更快的替代方案,它是为搜索代码而定制的。例如,它会自动忽略 .gitignore
中列出的文件和目录,因此您不必为 grep
或找到
。
I want to traverse all subdirectories, except the "node_modules" directory.
SOLUTION 1 (combine find
and grep
)
The purpose of this solution is not to deal with grep
performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.
Use find
, for excluding directories foo and bar :
find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print
Then combine find
and the non-recursive use of grep
, as a portable solution :
find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;
SOLUTION 2 (recursive use of grep
):
You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.
grep -R --exclude-dir=node_modules 'some pattern' /path/to/search
SOLUTION 3 (Ag)
If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in .gitignore
, so you don't have to keep passing the same cumbersome exclude options to grep
or find
.
这篇关于我如何从grep -R中排除目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!