如何在 Linux 中使用 grep 匹配一行中存在的两个字符串?


为了能够在 Linux 命令行中使用 **grep** 查找同一行上存在的两个字符串,我们首先必须了解 **grep** 命令是什么以及如何在 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() {}

现在,假设我有一个 **.txt** 文件,文件内容如下所示。

immukul@192 d2 % cat 2.txt
orange apple is great together

apple not great

is apple good

orange good apple not

现在,我想对包含两个单词 “apple” 和 “orange” 的所有行使用 **grep** 命令。

命令

grep 'orange' 2.txt | grep 'apple'

输出

immukul@192 d2 % grep 'orange' 2.txt | grep 'apple'

orange apple is great together
orange good apple not

更新于:2021年7月30日

980 次浏览

启动你的职业生涯

通过完成课程获得认证

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