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

find . | xargs grep "texthere" *

当前回答

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。

其他回答

在IBM AIX Server(操作系统版本:AIX 5.2)中,使用:

find ./ -type f -print -exec grep -n -i "stringYouWannaFind" {} \; 

这将打印出文件中的路径/文件名和相对行号,如:

./inc/xxxx_x.h

2865:/**描述:stringYouWanna查找*/

无论如何,这对我来说很有用:)

如果您只想跟踪实际的目录,而不是符号链接,

grep -r "thingToBeFound" directory

如果您希望遵循符号链接以及实际目录(注意无限递归),

grep -R "thing to be found" directory

由于您正在尝试递归grep,以下选项可能对您也有用:

-H: outputs the filename with the line

-n: outputs the line number in the file

因此,如果您希望在当前目录或任何子目录中查找包含达斯·维德的所有文件,并捕获文件名和行号,但不希望递归遵循符号链接,则命令如下

grep -rnH "Darth Vader" .

如果你想在目录中找到所有提到的单词cat

/home/adam/Desktop/TomAndJerry 

并且您当前在目录中

/home/adam/Desktop/WorldDominationPlot

如果您希望捕获字符串“cats”的任何实例的文件名而不是行号,并且希望递归在找到符号链接时遵循符号链接,您可以运行以下任一操作

grep -RH "cats" ../TomAndJerry                   #relative directory

grep -RH "cats" /home/adam/Desktop/TomAndJerry   #absolute directory

资料来源:

运行“grep--help”

对符号链接的简短介绍,对于任何阅读此答案并被我提到的符号链接所迷惑的人:https://www.nixtutor.com/freebsd/understanding-symbolic-links/

grep -r "texthere" .

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

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

也:

find ./ -type f -print0 | xargs -0 grep "foo"

但grep-r是更好的答案。

我想这就是你想写的

grep myText $(find .)

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

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