如何在 Linux 中限制 grep 返回的结果数量?


为了能够限制 grep 命令在 Linux 中返回的结果数量,我们首先需要了解 **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

语法

grep -rni "word" *

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

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

grep -rni "func main()" *

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

Learn Linux/Unix in-depth with real-world projects through our Linux/Unix certification course. Enroll and become a certified expert to boost your career.

输出

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

现在我们可以注意到有两个字符串与我们的 grep 查询匹配,我们可以使用以下命令来 **限制** 结果

命令

grep -m 1 'orange' 2.txt | grep 'apple

输出

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

orange apple is great together

更新于: 2021-07-30

883 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告