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

find . | xargs grep "texthere" *

当前回答

grep-r“texthere”。(通知期结束)

(^信用:https://stackoverflow.com/a/1987928/1438029)


澄清:

grep-r“texthere”/(递归地grep所有目录和子目录)

grep-r“texthere”。(递归地grep这些目录和子目录)

grep递归

grep[选项]模式[文件…][选项]-R、 -R,--递归递归地读取每个目录下的所有文件。这相当于-d recurse或--directories=recurse选项。http://linuxcommand.org/man_pages/grep1.html

grep帮助

$grep--帮助

$ grep --help |grep recursive
  -r, --recursive           like --directories=recurse
  -R, --dereference-recursive

选择

确认(http://beyondgrep.com/)

银(http://github.com/ggreer/the_silver_searcher)

其他回答

把我的两分钱扔在这里。正如其他人已经提到的那样,grep-r并不适用于所有平台。这听起来可能很傻,但我总是使用git。

git grep "texthere"

即使目录没有暂存,我也只是暂存并使用git grep。

只有文件名也很有用

grep -r -l "foo" .

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

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打印行号。

ag是我现在最喜欢的实现方式github.com/ggreer/the_silver_searcher。它基本上与ack相同,但还有一些优化。

这是一个简短的基准。我在每次测试前清除缓存(cfhttps://askubuntu.com/questions/155768/how-do-i-clean-or-disable-the-memory-cache )

ryan@3G08$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time grep -r "hey ya" .

real    0m9.458s
user    0m0.368s
sys 0m3.788s
ryan@3G08:$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time ack-grep "hey ya" .

real    0m6.296s
user    0m0.716s
sys 0m1.056s
ryan@3G08$ sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
3
ryan@3G08$ time ag "hey ya" .

real    0m5.641s
user    0m0.356s
sys 0m3.444s
ryan@3G08$ time ag "hey ya" . #test without first clearing cache

real    0m0.154s
user    0m0.224s
sys 0m0.172s