我如何在其文件内容中找到包含一个特定的文本序列的所有文件?

下一个不起作用. 它似乎显示系统中的每个单一文件。

find / -type f -exec grep -H 'text-to-find-here' {} \;

当前回答

下面的命令将为此做得很好:

find ./ -name "file_pattern_name"  -exec grep -r "pattern" {} \;

其他回答

您可以使用捕捉工具重复搜索当前文件夹,如:

grep -r "class foo" .

注意: -r - 重复搜索分支机构。

grep "class foo" **/*.c

如果你有错误,你的论点太长,考虑缩短你的搜索,或者使用找到合成代替,如:

find . -name "*.php" -execdir grep -nH --color=auto foo {} ';'

或者使用Ripgrep。

rg "class foo" .

它比任何其他工具,如 GNU/BSD grep, ucg, ag, sift, ack, pt 或类似,因为它是建立在Rust的 regex 引擎的顶部,使用终端自动化,SIMD和攻击性字体优化,使搜索非常快。


-i - 不敏感的搜索. -I - 忽略二进制文件. -w - 搜索完整的单词(相反的部分单词匹配)。 -n - 显示您的匹配线. -C/--背景(例如 -C5) - 增加背景,所以你看到周围的代码. --color=auto - 标记匹配文本. -H - 显示文件名,在文本中找到。

Silver Searcher 是一个可怕的工具,但 ripgrep 可能甚至更好。

它在Linux、Mac和Windows上运行,并在几个月前在Hacker News上编写(它有一个链接到Andrew Gallant的博客,其中有一个GitHub链接):

Ripgrep - 新命令线搜索工具

下面是可以用于搜索文件的几个命令列表。

grep "text string to search” directory-path

grep [option] "text string to search” directory-path

grep -r "text string to search” directory-path

grep -r -H "text string to search” directory-path

egrep -R "word-1|word-2” directory-path

egrep -w -R "word-1|word-2” directory-path

A Simple find can work handy. alias it in your ~/.bashrc 文件:

alias ffind find / -type f | xargs grep

开始一个新的终端和问题:

ffind 'text-to-find-here'

我的使用案例是找到我写的Python代码,我写的JSON线的某种方式,我知道JSONL将是函数名称的一部分,到_JSON将出现在身体中,但没有更多的东西。

尽管有 50 个答案,但在同一文件中找到多个字符串(无论是在同一行中还是不在同一行中)并没有得到答案。

格雷普中的 -q 是安静的. 没有什么是打印,只有返回值是设置的. 因此,在结尾的 - 打印. 每个 -exec 只运行,如果前一个成功。

find . -type f -name "*.py" \
  -exec grep -q -e 'to_json' {} \; \
  -exec grep -q -e 'def\s.*jsonl' {} \; \
  -print