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

find . | xargs grep "texthere" *

当前回答

另一种语法递归地grep Linux系统上所有文件中的字符串

grep-irn“字符串”

-r表示递归搜索,在给定目录和子目录中搜索指定字符串,在文件、程序等中查找指定字符串

-不区分大小写可用于添加大小写颠倒的字符串

-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

这里有一个递归(使用bash和sh进行了少量测试)函数,它遍历给定文件夹($1)的所有子文件夹,并使用grep搜索给定文件($2)中的给定字符串($3):

$ cat script.sh
#!/bin/sh

cd "$1"

loop () {
    for i in *
    do
        if [ -d "$i" ]
        then
            # echo entering "$i"
            cd "$i"
            loop "$1" "$2"
        fi
    done

    if [ -f "$1" ]
    then
        grep -l "$2" "$PWD/$1"
    fi

    cd ..
}

loop "$2" "$3"

运行它和示例输出:

$ sh script start_folder filename search_string
/home/james/start_folder/dir2/filename

如果您知道所需文件的扩展名或模式,另一种方法是使用--include选项:

grep -r --include "*.txt" texthere .

您还可以使用--exclude提及要排除的文件。

Ag

如果您经常搜索代码,Ag(银搜索器)是grep的一个更快的替代方案,它是为搜索代码而定制的。例如,默认情况下,它是递归的,并自动忽略.gitignore中列出的文件和目录,因此您不必一直向grep或find传递同样繁琐的排除选项。

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

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/

只是为了好玩,如果@christangrant的答案太多而无法输入,可以快速搜索*.txt文件:-)

grep-r文本此处|grep.txt文件