代码之家  ›  专栏  ›  技术社区  ›  IAspireToBeGladOS

使用sed-如何用未知内容替换两个HTML标记或模式?

  •  -1
  • IAspireToBeGladOS  · 技术社区  · 7 年前

    我希望保留标签之间的未知内容不变,但希望匹配使用以下内容的所有标签:

    <div class="section1-title">arbitrary content here</div>
    

    并将周围的标记替换为:

    <h2>arbitrary content here</h2>
    

    我提出了以下内容,但显然它没有像在第二部分中那样起作用,它实际上是在替换“].*[<]/h2[>]“对于找到的每个匹配项。

    sed -i 's/[<]div class=\"section1-title\"[>].*[<]\/div[>]/<h2[>].*[<]\/h2[>]/g'
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mixolydian    7 年前

        bash-3.2$ sed 's/<div class=\"section1-title\">\(.*\) 
        <\/div>/<h2>\1<\/h2>/g' <<< '<div class="section1-title">arbitrary 
        content here</div>'
        <h2>arbitrary content here</h2>
    

    内容周围的括号- \(.*\) -允许以后引用它,就像使用 \1 .

    https://www.regular-expressions.info/backref.html

    .bash_profile sed: \1 not defined in the RE 解释一下为什么括号应该在正则表达式中转义。

    推荐文章