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

find . | xargs grep "texthere" *

当前回答

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

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 --help 

返回当前目录中此处的regexp文本的所有匹配项,以及相应的行号:

grep -rn "texthere" .

返回文本的所有匹配项,从根目录开始,具有相应的行号,忽略大小写:

grep -rni "texthere" /

此处使用的标志:

-r递归-n带输出的打印行号-我不理这个案子

我想这就是你想写的

grep myText $(find .)

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

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

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

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/

如果您正在从目录结构中查找所有文件中的特定内容,您可以使用find,因为它更清楚您在做什么:

find -type f -exec grep -l "texthere" {} +

注意,-l(l的小写)显示包含文本的文件的名称。如果要打印匹配项本身,请将其删除。或者使用-H将文件与匹配项一起获取。总之,其他备选方案包括:

find -type f -exec grep -Hn "texthere" {} +

其中-n打印行号。

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

对于UNIX命令是:

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

对于Linux,命令是:

grep -r "string to be searched" .