regex - 提取模式之间的内容

标签 regex linux shell awk sed

在 SUSE Linux 上,我想从文本文件中找到 BEGIN 字符串和 END 字符串之间的完整部分。我考虑过使用 sed 或 awk。

可选地,我想在另一次运行中搜索下一个事件。

  • 它应该成为 bash 脚本的一部分
  • 结果应该写入文件

我的挑战是:

  • BEGIN 字符串在 END 字符串出现之前多次出现
  • BEGIN 字符串有时在同一行之前有其他字符
  • END 字符串有时在同一行后面有其他字符

例子

something before ----BEGIN
first paragraph
Text Text Text
Text Text Text
Text Text Text
no ending pattern

something before ----BEGIN
second paragraph
Text Text Text
Text Text Text
Text Text Text
END---- some more text

no beginning pattern
Text Text Text
Text Text Text
END---- some more text

something before ----BEGIN
third paragraph
Text Text Text
Text Text Text
Text Text Text
no ending pattern

something before ----BEGIN
fourth paragraph
Text Text Text
Text Text Text
Text Text Text
END---- some more text

Text Text Text

我期待这样的事情:

----BEGIN
second paragraph
Text Text Text
Text Text Text
Text Text Text
END----

在另一次运行中,我想找到下一个完整的部分:

----BEGIN
fourth paragraph
Text Text Text
Text Text Text
Text Text Text
END----

在论坛中我已经可以找到类似这样的内容:

tac < file.txt | sed  '/END-----/,$!d;/-----BEGIN/q' | tac

但它只找到最后一次出现的字符,而不会剪切开头和结尾的字符。

不幸的是,我在使用 sed/awk 或正则表达式方面经验不足。 如果您能给我一些指导,我将不胜感激!

干杯,呃

最佳答案

$ cat tst.awk
BEGIN { beg="----BEGIN"; end="END----" }
sub(".*"beg,beg) { inBlock=1; buf="" }
inBlock {
    buf = buf $0 ORS
    if ( sub(end".*",end,buf) ) {
        print buf ORS
        inBlock=0
    }
}

$ awk -f tst.awk file
----BEGIN
second paragraph
Text Text Text
Text Text Text
Text Text Text
END----

----BEGIN
fourth paragraph
Text Text Text
Text Text Text
Text Text Text
END----

关于regex - 提取模式之间的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825722/

相关文章:

php - 如何隔离内容直到第一个双换行序列?

linux - 我如何使用 cli 列出所有带有特定标签的 S3 存储桶?

c - Linux 中的 getch() 和 getche() 等价于什么?

java - 从java运行linux命令,错误500,无法运行程序没有那个文件或目录

Linux - 通过将最后一个连字符替换为 '##' 来重命名所有文件

javascript - 奇怪的 JavaScript 习语 - "/xyz/.test(function(){xyz;})"是做什么的?

regex - 基本正则表达式 URL 匹配

shell - 在 Amazon EC2 中启动实例时传递脚本

r - 从具有逗号分隔值的列中提取多个字符串

linux - 如何在 Intel CPU 上找到 L3 Cache 参数?