【问题标题】:Remove lines between matching PAIR of pattern删除匹配 PAIR 模式之间的行
【发布时间】:2016-08-30 11:24:11
【问题描述】:

我有一个包含一些循环模式的文本文件,我想删除每个匹配的 pair 匹配模式之间的行。

问题:“图案线”最后出现的是“开口图案”。

例子:

Some lines
In the preamble
START
Some lines       # Remove this
I with to remove # Remove this
STOP             # Remove this
Some lines
I wish to keep
START
Some other lines # Remove this
I with to remove # Remove this
STOP             # Remove this
Some lines
I wish to keep
START
Don't remove this line
Etc.

所以我想删除STARTSTOP 之间的所有内容,而不是最后一次出现START 之后的内容

如果我的原始文本在最后一个关闭模式之后没有最后一次出现打开模式(例如here),我发现了许多使用 sed 和 awk 的解决方案可能对我有用,但可惜这不是解决我的问题。

奖励:理想情况下,我想删除包含结束模式的行,而不是开始模式。这并不是很重要,因为我总是可以保留两者并在之后删除关闭的。

我实际上希望清理一个巨大的 pdf 文档的书签,该文档由几个较小的文档串联而成,每个文档已经包含多个书签,以仅保留每个原始文件中的第一个书签。 也欢迎任何有关实现此目标的替代方案的建议。

【问题讨论】:

    标签: bash awk sed


    【解决方案1】:
    $ awk '/START/,/STOP/{if($0=="START") a=""; else {a=a $0 ORS;next}} {print} END {printf "%s", a}' file
    Some lines
    In the preamble
    START
    Some lines
    I wish to keep
    START
    Some lines
    I wish to keep
    START
    Don't remove this line
    Etc.
    

    步行:

    /START/,/STOP/ {     # between markers
        if($0=="START")  # if START
            a=""         # reset a and print record in the end
        else {
            a=a $0 ORS   # build up a
            next         # skip the print in the end
        }
    } 
    {
        print            # the print
    } 
    END {
        printf "%s", a   # in the end print the a
    }
    

    【讨论】:

      最近更新 更多