gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:25:49 25 4
gpt4 key购买 nike

比如有一段文字

[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com