如何在 Linux 中搜索某个目录及其所有子目录中的字符串?


Linux 中的 **grep** 命令用于在文件中搜索特定字符模式。它是 Linux 中最常用的实用程序命令之一,用于显示包含我们尝试搜索的模式的行。

通常,我们尝试在文件中搜索的模式被称为正则表达式。

语法

grep [options] pattern [files]

虽然有很多不同的选项可供我们使用,但其中一些最常用的选项是 -

-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern

现在,让我们考虑一个案例,我们想要在特定目录(例如 dir1)中的所有文件中查找特定模式。

语法

grep -rni "word" *

在上述命令中,用以下内容替换“word”占位符:

为此,我们使用以下命令 -

grep -rni "func main()" *

上述命令将尝试在特定目录中的所有文件以及子目录中查找字符串“func main()”。

输出

main.go:120:func main() {}

如果我们只想在单个目录中查找特定模式,而不是子目录,则需要使用以下命令 -

grep -s "func main()" *

在上述命令中,我们使用了 **-s** 标志,它将帮助我们避免在运行命令的目录中存在的每个子目录都收到警告。

输出

main.go:120:func main() {}

另一个我们可以使用的命令是 find 命令。

命令

find . -name "*.go" -exec grep -H "func main" {} \;

输出

./main.go:func main() {

更新于: 2021-07-30

4K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.