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

find . | xargs grep "texthere" *

当前回答

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

git grep "texthere"

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

其他回答

grep -r "texthere" .

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

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

我想这就是你想写的

grep myText $(find .)

如果你想找到grep命中的文件,这可能是其他有用的东西

grep myText $(find .) | cut -d : -f 1 | sort | uniq

我现在总是使用(即使在Windows上使用GoW-Gnu):

grep --include="*.xxx" -nRHI "my Text to grep" *

(正如kronen在评论中指出的,您可以添加2>/dev/null以使拒绝权限的输出无效)

其中包括以下选项:

--include=PATTERN

仅在目录中重复搜索与PATTERN匹配的文件。

-n, --line-number

在输出的每一行前面加上输入文件中的行号。

(注意:phuclv在注释中补充道,-n会大大降低性能,因此您可能希望跳过该选项)

-R, -r, --recursive

递归地读取每个目录下的所有文件;这相当于-d递归选项。

-H, --with-filename

打印每个匹配项的文件名。

-I     

处理二进制文件,就像它不包含匹配的数据一样;这相当于--binary files=不匹配选项。

如果我想要不区分大小写的结果,我可以添加“I”(-nRHIi)。

我可以得到:

/home/vonc/gitpoc/passenger/gitlist/github #grep --include="*.php" -nRHI "hidden" *
src/GitList/Application.php:43:            'git.hidden'      => $config->get('git', 'hidden') ? $config->get('git', 'hidden') : array(),
src/GitList/Provider/GitServiceProvider.php:21:            $options['hidden'] = $app['git.hidden'];
tests/InterfaceTest.php:32:        $options['hidden'] = array(self::$tmpdir . '/hiddenrepo');
vendor/klaussilveira/gitter/lib/Gitter/Client.php:20:    protected $hidden;
vendor/klaussilveira/gitter/lib/Gitter/Client.php:170:     * Get hidden repository list
vendor/klaussilveira/gitter/lib/Gitter/Client.php:176:        return $this->hidden;
...

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

grep-irn“字符串”

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

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

-n打印指定字符串的行号

注意:这会将大量结果打印到控制台,所以您可能需要通过管道过滤输出,并删除不太有趣的信息,它还会搜索二进制程序,因此您可能需要过滤一些结果

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。