如何递归地grep所有目录和子目录?

find . | xargs grep "texthere" *

当前回答

这应该是有效的:

grep -R "texthere" *

其他回答

只有文件名也很有用

grep -r -l "foo" .

2018年,您希望使用ripgrep或白银搜索器,因为它们比其他搜索器快得多。

下面是一个包含336个一级子目录的目录:

% find . -maxdepth 1 -type d | wc -l
     336

% time rg -w aggs -g '*.py'
...
rg -w aggs -g '*.py'  1.24s user 2.23s system 283% cpu 1.222 total

% time ag -w aggs -G '.*py$'
...
ag -w aggs -G '.*py$'  2.71s user 1.55s system 116% cpu 3.651 total

% time find ./ -type f -name '*.py' | xargs grep -w aggs
...
find ./ -type f -name '*.py'  1.34s user 5.68s system 32% cpu 21.329 total
xargs grep -w aggs  6.65s user 0.49s system 32% cpu 22.164 total

在OSX上,这将安装rigrep:brew install rigrep。这将安装silver搜索器:brew install the _silver_searcher。

我想这就是你想写的

grep myText $(find .)

如果你想找到grep命中的文件,这可能是其他有用的东西

grep myText $(find .) | cut -d : -f 1 | sort | uniq

注意这个发现-当查找匹配的文件太多时,键入f | xargs grep任何类型的解决方案都会遇到“Argument list to long”错误。

最好的选择是grep-r,但如果不可用,请使用find-键入f-exec grep-H whatever{}\;相反

在POSIX系统中,找不到grep的-r参数和grep-rn“东西”。不会运行,但如果使用find命令,它将:

查找-键入f-exec grep-n“stuff”{}\-打印

Solaris和HP-UX同意。