在Windows中,我会在文件夹中搜索一个单词。类似地,我想知道特定的单词是否出现在包含许多子目录和文件的目录中。我对grep语法的搜索显示我必须指定文件名,即grep字符串文件名。
现在,我不知道文件名,我该怎么做? 一个朋友建议做grep -nr字符串,但我不知道这意味着什么,我没有得到任何结果(没有响应,直到我发出Ctrl + C)。
在Windows中,我会在文件夹中搜索一个单词。类似地,我想知道特定的单词是否出现在包含许多子目录和文件的目录中。我对grep语法的搜索显示我必须指定文件名,即grep字符串文件名。
现在,我不知道文件名,我该怎么做? 一个朋友建议做grep -nr字符串,但我不知道这意味着什么,我没有得到任何结果(没有响应,直到我发出Ctrl + C)。
当前回答
Grep -r "yourstring" * 会发现“你的字符串”在任何文件和文件夹
现在,如果你想同时查找两个不同的字符串,你可以使用选项E并为搜索添加单词。休息之后的例子
grep -rE "yourstring|yourotherstring|$" *将搜索yourstring或yourotherstring匹配的列表位置
其他回答
下面的示例递归地查找位于文件夹path1、path2和path3中的*.xml和*.js文件中的搜索字符串。
grep -r --include=*.xml --include=*.js "your search string" path1 path2 path3
因此,您可以在文件的子集中搜索许多目录,只需在最后提供路径。
你选择的答案是好的,它是可行的,但它不是正确的方法,因为:
grep -nr yourString* .
这实际上是搜索字符串"yourStrin"和"g" 0或多次。
所以正确的做法是:
grep -nr \w*yourString\w* .
此命令在当前文件夹上搜索包含前后任意字符的字符串。
我喜欢使用的另一个选项:
find folder_name -type f -exec grep your_text {} \;
-type f只返回文件而不返回文件夹
-exec and{}在搜索中找到的文件上运行grep(准确的语法是“-exec command{}”)。
还有:
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。下载Silver Searcher或ripgrep。它们都很出色,并且比grep或ack快得多,有大量的选项。