在Windows中,我会在文件夹中搜索一个单词。类似地,我想知道特定的单词是否出现在包含许多子目录和文件的目录中。我对grep语法的搜索显示我必须指定文件名,即grep字符串文件名。

现在,我不知道文件名,我该怎么做? 一个朋友建议做grep -nr字符串,但我不知道这意味着什么,我没有得到任何结果(没有响应,直到我发出Ctrl + C)。


当前回答

grep -R "string" /directory/

当-R不跟随符号链接时,-R也跟随符号链接。

其他回答

还有:

find directory_name -type f -print0 | xargs -0 grep -li word

但这对初学者来说可能有点多。

find is a general purpose directory walker/lister, -type f means "look for plain files rather than directories and named pipes and what have you", -print0 means "print them on the standard output using null characters as delimiters". The output from find is sent to xargs -0 and that grabs its standard input in chunks (to avoid command line length limitations) using null characters as a record separator (rather than the standard newline) and then applies grep -li word to each set of files. On the grep, -l means "list the files that match" and -i means "case insensitive"; you can usually combine single character options so you'll see -li more often than -l -i.

如果您不使用-print0和-0,那么您将遇到包含空格的文件名的问题,因此使用它们是一个好习惯。

为什么不做一个递归搜索来找到子目录中的所有实例:

grep -r 'text' *

这就像一个咒语。

下面的示例递归地查找位于文件夹path1、path2和path3中的*.xml和*.js文件中的搜索字符串。

grep -r --include=*.xml --include=*.js "your search string" path1 path2 path3

因此,您可以在文件的子集中搜索许多目录,只需在最后提供路径。

grep -nr string my_directory

附加说明:这满足grep [options] string filename语法,因为在类unix系统中,目录是一种文件(有一个术语“常规文件”专门指在Windows中被称为“文件”的实体)。

grep -nr string从标准输入读取内容进行搜索,这就是为什么它只是等待你的输入,并在你按^C时停止这样做(它也会在^D时停止,这是文件结束的组合键)。

GREP:全局正则表达式打印/解析器/处理器/程序。 您可以使用它来搜索当前目录。 你可以为“递归”指定-R,这意味着程序在所有子文件夹中搜索,以及它们的子文件夹,以及它们的子文件夹的子文件夹,等等。

grep -R "your word" .

-n将打印行号,即它在文件中匹配的行号。 -i将搜索不区分大小写(大写/非大写字母)。

grep -inR "your regex pattern" .