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

find . | xargs grep "texthere" *

当前回答

在POSIX系统中,找不到grep的-r参数和grep-rn“东西”。不会运行,但如果使用find命令,它将:

查找-键入f-exec grep-n“stuff”{}\-打印

Solaris和HP-UX同意。

其他回答

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

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。

grep -r "texthere" .

第一个参数表示要搜索的正则表达式,而第二个参数表示应该搜索的目录。在这种情况下。表示当前目录。

注意:这适用于GNUgrep,在某些平台(如Solaris)上,您必须特别使用GNUgrep而不是传统实现。对于Solaris,这是ggrep命令。

下面是在Unix和Linux环境中递归搜索字符串的命令。

对于UNIX命令是:

find . -name "string to be searched" -exec grep "text" "{}" \;

对于Linux,命令是:

grep -r "string to be searched" .

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

git grep "texthere"

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