使用查找命令find

我们还可以组合使用 find 和 grep 命令来更有效地在许多文件中搜索文本字符串。

# find/-exec grep -l "your-text-to-find" {} ;

要搜索特定的文件扩展名文件,例如仅在所有 php 文件中搜索“your-text”,请使用以下命令:

# find/-name '*.php' -exec grep -l "your-text" {} ;
如何在 Linux 上查找包含特定文本的所有文件

许多最近的文件管理器支持直接在文件列表中搜索文件。
无论如何,它们中的大多数都不允许我们在文件内容中进行搜索。
以下是一些可用于使用命令行在 Linux 上搜索文件内容的方法。
在这篇文章中,我们将展示“grep”、“ripgrep”、“ack”和“find”命令。

使用 ack 命令

此命令将允许我们搜索整个文件系统或者所需的路径。
它可以比 grep 更容易使用。

  • 要在当前路径中搜索,请使用以下命令行:
ack "your-text-to-find"
  • 要在整个文件系统中搜索,请将目录更改为根 (/),如下所示:
ack "your-text-to-find" /

对于 ripgrep 和 ack 命令,使用正则表达式来指定文件类型。

使用 grep 命令

查找包含特定文本的文件的最佳方法是使用 grep 命令。
它旨在根据整个数据流中的模式查找包含必要文本的文件。
我们需要使用以下命令:

grep -rnw '/path/to/somewhere/' -e 'pattern'

其中r代表递归,n代表行号,w用来匹配整个单词,'/path/to/somewhere/'是目录,'pattern'是你在文件中查找的文本.

为了使搜索更有效,我们还可以添加诸如 --exclude、--include、--exclude-dir 等可选设置。

  • 要仅搜索具有 .c 或者 .h 扩展名的文件,请使用以下命令:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
  • 要排除以 .o 扩展名结尾的所有文件的搜索,请尝试以下操作:
grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
  • 要从搜索中排除特定目录,我们需要:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

我们还可以使用 grep 运行另一个命令行:

grep -iRl "your-text-to-find" ./

这里 i 代表忽略大小写,R 代表递归,I 用于显示文件名,而不是结果本身,./代表从机器的根开始。

使用 ripgrep 命令

grep 的另一种用途是 ripgrep。
如果我们正在处理大型项目或者大文件,则最好使用 ripgrep。
它看起来像这样:

rg "your-text-to-find" /
日期:2020-06-02 22:18:31 来源:oir作者:oir