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

find . | xargs grep "texthere" *

当前回答

这是在我当前的机器上(windows 7上的git bash)适用于我的案例的例子:

find ./ -type f -iname "*.cs" -print0 | xargs -0 grep "content pattern"

对于带有空格的路径,我总是忘记-print0和-0。

编辑:我的首选工具现在是ripgrep:https://github.com/BurntSushi/ripgrep/releases . 它真的很快,并且有更好的默认值(比如默认情况下的递归)。与我的原始答案相同的示例,但使用了ripgrep:rg-g“*.cs”“content pattern”

其他回答

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

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

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。

下面是在Unix和Linux环境中递归搜索字符串的命令。

对于UNIX命令是:

find . -name "string to be searched" -exec grep "text" "{}" \;

对于Linux,命令是:

grep -r "string to be searched" .

要查找路径递归包含特定字符串的文件名,请使用以下命令对于UNIX:

find . | xargs grep "searched-string"

对于Linux:

grep -r "searched-string" .

在UNIX服务器上查找文件

find . -type f -name file_name

在LINUX服务器上查找文件

find . -name file_name
grep -r "texthere" .

第一个参数表示要搜索的正则表达式,而第二个参数表示应该搜索的目录。在这种情况下。表示当前目录。

注意:这适用于GNUgrep,在某些平台(如Solaris)上,您必须特别使用GNUgrep而不是传统实现。对于Solaris,这是ggrep命令。