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

htzpubme  于 2022-11-16  发布在  Shell
关注(0)|答案(3)|浏览(194)

例如,有一段文字

[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

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

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

以获取带有[task]的行并将其重定向到另一个文件。请帮助我完成此操作。

wbgh16ku

wbgh16ku1#

请尝试以下操作:

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
rxztt3cl

rxztt3cl2#

您可以使用此awk

awk 'NF == 2 {isTask = ($1 ~ /^\[task/)} isTask' file

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

2hh7jdfx3#

我会利用GNU AWK来完成这个任务,让file.txt内容

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

然后

awk 'BEGIN{RS="[";ORS=""}/task/{print "[" $0}' file.txt

给出输出

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

说明:我告诉GNU AWK行分隔符(RS)是[和输出行分隔符(ORS)是空字符串,即行是[[之间的东西,则对于在I print内具有task的每一行,其具有前置的[,因为ORS是空字符串,所以没有添加多余的换行符(所需的换行符已经在行中)。如果想了解更多关于RSORS的信息,请阅读8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

  • (在gawk 4.2.1中测试)*

相关问题