【问题标题】:Sed: regular expression match lines without <!--sed:正则表达式匹配不带 <!-- 的行
【发布时间】:2010-04-08 03:55:38
【问题描述】:

我有一个 sed 命令来注释掉 xml 命令

sed 's/^\([ \t]*\)\(.*[0-9a-zA-Z<].*\)$/\1<!-- Security: \2 -->/' web.xml 

拍摄:

<a>

  <!-- Comment -->
  <b>
    bla
  </b>

</a>

生产:

<!-- Security: <a> -->

  <!-- Security: <!-- Comment --> -->    // NOTE: there are two end comments.  
  <!-- Security: <b> -->
    <!-- Security: bla -->
  <!-- Security: </b> -->

<!-- Security: </a> -->

理想情况下,我不想使用我的 sed 脚本来评论已评论的内容。

即:

<!-- Security: <a> -->

  <!-- Comment -->
  <!-- Security: <b> -->
    <!-- Security: bla -->
  <!-- Security: </b> -->

<!-- Security: </a> -->

我可以这样做:

sed 's/^\([ \t]*\)\(.*[0-9a-zA-Z<].*\)$/\1<!-- Security: \2 -->/' web.xml
sed 's/^[ \t]*<!-- Security: \(<!--.*-->\) -->/\1/' web.xml

但我认为单线更清洁(?)

这很相似:matching a line that doesn't contain specific text with regular expressions

【问题讨论】:

    标签: regex sed


    【解决方案1】:

    这似乎行得通。

    ^([ \t]*)(?!<!--)([0-9a-zA-Z<].*)$
    

    你必须避开 parenteses 和其他东西才能真正使用 sed。

    在在线regular expression tester 中测试了表达式。

    不幸的是,sed 似乎不支持前瞻(但sseddoes)。
    也许你应该试试awkssed

    【讨论】:

    • 是的,我已经尝试过(以及不同的变体),但我无法让它工作。它最终没有突出显示。
    • 进一步阅读后,似乎 sed 不支持这些表达式。您必须使用 ssed 和活动 perl 模式 (-R)。在这里找到该信息:sed.sourceforge.net/sedfaq6.html
    • 酷。我也是这么想的。 +1 澄清
    【解决方案2】:

    您可以使用 awk,如果我的要求正确:

    awk -F"," '!/<!--/&&NF{$0="<!-- Security: "$0"-->"}1' file
    

    【讨论】:

    • 嗯,真的更喜欢使用 sed,但 +1 用于建议。
    【解决方案3】:

    结束了这个:

    startInsert="<!-- Security: "
    endInsert=" -->"
    
    whiteSpace="[ \t]*"
    char="[0-9a-zA-Z^_)!-/:-@[-\{-~]"
    
    sed "s/^\($whiteSpace\)\(.*$char.*\)$/\1$startInsert\2$endInsert/" $file 
    sed "s/^\($whiteSpace\)$startInsert\(<!--.*\-->\)$endInsert/\1\2/" $file 
    

    不像我希望的那样优雅,但就像一个魅力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-06
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 2018-05-25
      • 2019-03-10
      • 1970-01-01
      相关资源
      最近更新 更多