regex - 如何在正则表达式匹配后打印下几行直到另一个正则表达式匹配?

标签 regex shell awk

比如有一段文字

[task,line:111] first
                second
[demo,line:222] first
[test,line:333] first
[task,line:444] first
                second
                third
[task,line:555] first

我只想要带有 [task] 的行和下一行,直到另一个 [*] 出现。如下图

[task,line:111] first
                second
[task,line:444] first
                second
                third
[task,line:555] first

如何在 shell 脚本中使用 awk 或其他工具来完成它? 我只知道我可以使用

awk '/regex/{print $0>"'$output'"}' $file

使用 [task] 获取行并将它们重定向到另一个文件。请帮助我。

最佳答案

请您尝试以下操作:

awk '
    /^\[/ {                                     # the line starts with "["
        if ($1 ~ /^\[task/) f = 1               # set flag for "[task" line
        else f = 0                              # otherwise reset the flag
    }
    f {print}                                   # if flag is set, print the line
' input_file > output_file

然后 output_file 将如下所示:

[task,line:111] first
                second
[task,line:444] first
                second
                third
[task,line:555] first

关于regex - 如何在正则表达式匹配后打印下几行直到另一个正则表达式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74285118/

相关文章:

javascript - 使用正则表达式匹配多个结果

linux - 使用点空格与点斜线执行文件

linux - 如果否则用 rm Shell linux

bash - 如何在 bash 中使用 awk 遍历一个字段的多个值?

linux - 聚合行和求和列

java - 如何去掉 String[] 中的空格?

javascript - 用于捕获第一个父级的子级属性值的正则表达式

shell - 在 shell 脚本中调用的脚本文件中调用主脚本函数

bash - 如何使用 bash 或 awk 对多个文件中的矩阵求和

javascript - JavaScript 的 MAC 地址正则表达式