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

find . | xargs grep "texthere" *

当前回答

2018年,您希望使用ripgrep或白银搜索器,因为它们比其他搜索器快得多。

下面是一个包含336个一级子目录的目录:

% find . -maxdepth 1 -type d | wc -l
     336

% time rg -w aggs -g '*.py'
...
rg -w aggs -g '*.py'  1.24s user 2.23s system 283% cpu 1.222 total

% time ag -w aggs -G '.*py$'
...
ag -w aggs -G '.*py$'  2.71s user 1.55s system 116% cpu 3.651 total

% time find ./ -type f -name '*.py' | xargs grep -w aggs
...
find ./ -type f -name '*.py'  1.34s user 5.68s system 32% cpu 21.329 total
xargs grep -w aggs  6.65s user 0.49s system 32% cpu 22.164 total

在OSX上,这将安装rigrep:brew install rigrep。这将安装silver搜索器:brew install the _silver_searcher。

其他回答

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

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

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

Ag

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

要查找路径递归包含特定字符串的文件名,请使用以下命令对于UNIX:

find . | xargs grep "searched-string"

对于Linux:

grep -r "searched-string" .

在UNIX服务器上查找文件

find . -type f -name file_name

在LINUX服务器上查找文件

find . -name file_name

这里有一个递归(使用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

在IBM AIX Server(操作系统版本:AIX 5.2)中,使用:

find ./ -type f -print -exec grep -n -i "stringYouWannaFind" {} \; 

这将打印出文件中的路径/文件名和相对行号,如:

./inc/xxxx_x.h

2865:/**描述:stringYouWanna查找*/

无论如何,这对我来说很有用:)

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

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

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

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

其中-n打印行号。