我如何从grep -R中排除目录? [英] How can I exclude directories from grep -R?

查看:131
本文介绍了我如何从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

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆