【问题标题】:sed (awk?) to remove nearly duplicate linessed (awk?) 删除几乎重复的行
【发布时间】:2015-04-29 17:40:51
【问题描述】:

我有一个将 HTML 样式的 cmets 与其真实文本交替的文件:

<!-- Here's a first line -->
Here's a first line
<!-- Here's a second line -->
Here's a third line

如果注释除了标签本身之外与以下行相同,我想删除它,否则保留它:

Here's a first line
<!-- Here's a second line -->
Here's a third line

我在这里阅读了类似的问题,但无法根据我的情况推断解决方案。

【问题讨论】:

    标签: bash awk sed


    【解决方案1】:
    sed '/^<!-- \(.*\) -->$/N;s/^<!-- \(.*\) -->\n\1$/\1/'
    #
    #    /^<!-- \(.*\) -->$/   match an HTML comment as its own line, in which case
    #                       N; add the next line to the pattern space and keep going
    # 
    #                         s/^<!-- \(.*\) -->\n\1$/     detect a comment as you
    #                                                 \1/  described and replace it
    #                                                      appropriately
    

    如图:

    $ sed '/^<!-- \(.*\) -->$/N;s/^<!-- \(.*\) -->\n\1$/\1/' <<EOF
    > <!-- Foo -->
    > Foo
    > <!-- Bar -->
    > Baz
    > <!-- Quux -->
    > Quux
    > 
    > Something
    > Something
    > Another something
    > EOF
    

    给予:

    Foo
    <!-- Bar -->
    Baz
    Quux
    
    Something
    Something
    Another something
    

    您可能需要调整它来处理缩进,但这应该不会太令人惊讶。您可能还想切换到sed -r,这将要求括号不被转义。

    【讨论】:

      【解决方案2】:

      你可以使用这个awk

      awk '/<!--.*?-->/{h=$0; gsub(/ *(<!--|-->) */, ""); s=$0; next}
            $0!=s{$0=h ORS $0} 1' file.html
      Here's a first line
      <!-- Here's a second line -->
      Here's a third line
      

      【讨论】:

      • ? 中的 /&lt;!--.*?--&gt;/ AFAIK 什么也没做。如果它正在做某事 - 什么?
      • 是的,没错,我认为.*? 在这里的行为与.* 相同。
      • 我只是不知道 awk 将该声明中的 ? 视为什么。我本来以为可能是文字?,但显然不是。它也不能将 *? 视为文字 * 的零次或 1 次出现,否则整个正则表达式将不匹配任何输入。我猜它会将其视为 .* 所代表的任何字符的 0 次或多次重复出现 0 次或 1 次,即与 (.*)? 相同,这是无用的,但至少并非毫无意义。
      【解决方案3】:

      这可能对你有用(GNU sed):

      sed -r '$!N;/<!-- (.*) -->\n\1$/!P;D' file
      

      这会比较整个文件中所有连续行的请求条件,如果找到则不打印该对的第一行。

      注意这迎合了连续的评论行

      【讨论】:

        猜你喜欢
        • 2011-06-01
        • 2019-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多