如何在 Linux 中使用 grep 命令搜索多行模式?
linuxoperating systemopen source
为了能够在文件中搜索多行包含特定模式的内容,我们将使用 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()" *
现在假设我们有一个名为 sample.txt 的文本文件,其内容如下所示。
$ immukul@192 linux-questions-code % cat sample.txt blabla blabla foofoo here is the text2strike Just a pattern bar blabla blabla
下面显示的是搜索多行模式的命令
grep -Pzo "(?s)^(\s*)\N*/foo/,/bar/p.*?{.*?^\1}" .txt
输出
foofoo here is the text2strike just a pattern bar
相关文章
有用资源
linux 参考教程 - 该教程包含有关 linux 的更多信息:https://www.cainiaomax.com/linux/

