【问题标题】:Sed expression to match this multiline code?sed 表达式来匹配这个多行代码?
【发布时间】:2018-03-21 15:54:58
【问题描述】:

假设以下代码sn-p:

  <head>
     <script>....</script>
     <script>....</script>
  </head>
  <body>
    <script>
      some stuff
      a change
      more stuff
      more changes
      more stuff
            }
          }
        }
      }
     final changes
    </script>
  </body>

我需要在最后一个&lt;/script&gt; 之前添加一些内容,即final changes。我怎样才能告诉 sed 匹配那个? final changes 不存在,脚本的最后几行就像四五行},所以会是这样的场景,我需要匹配多行。

所有其他更改都通过匹配行替换,然后替换为line + the changes。但是我不知道如何匹配多行以将&lt;/script&gt;&lt;/body&gt;替换为final changes &lt;/script&gt;&lt;/body&gt;

我尝试使用与替换多行相同的策略,但没有奏效,继续报告unterminated substitute pattern

sed 's|</script>\
   </body>|lalalalala\
   </script>\
   </body>|' file.hmtl

我已经阅读了这个问题Sed regexp multiline - replace HTML,但它不适合我的特殊情况,因为它匹配搜索选项之间的所有内容。我需要匹配一些东西,然后在第一个搜索运算符之前添加一些东西。

【问题讨论】:

    标签: sed


    【解决方案1】:

    sedgrepawk 等不适用于 XML/HTML 处理。
    使用适当的 XML/HTML 解析器。

    xmlstarlet 就是其中之一。
    样品file.html:

    <html>
    <head>
         <script>....</script>
         <script>....</script>
      </head>
      <body>
        <script>
          var data = [0, 1, 2];
          console.log(data);
        </script>
      </body>
    </html>
    

    命令:

    xmlstarlet ed -O -P -u '//body/script' -v 'alert("success")' file.htm
    

    输出:

    <html>
    <head>
         <script>....</script>
         <script>....</script>
      </head>
      <body>
        <script>alert("success")</script>
      </body>
    </html>
    

    http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html

    【讨论】:

    • 我同意xmlstarlet 是要走的路,但不幸的是,与jq 一样,世界上只有3 个人知道如何使用这两种方法!你知道任何解释如何使用它的好资源,凡人都能理解吗?
    • @MarkSetchell,没问题,添加了xmlstarlet指南链接
    • 如果我想替换特定标签之间的内容,这个解决方案是正确的,即 HTML 解析器。但这不是我的情况,我不是在解析 HTML,我对替换文件中的特定字符串感兴趣(无论是 HTML、C++ 还是随机文本文件都无关紧要)。检查问题中已编辑的 sn-p。
    【解决方案2】:

    终于在https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-stringxara的回答下得到了这个

    总而言之,与其尝试用 sed 变魔术,不如将换行符替换为 sed 可以理解的字符(如 \r),执行替换,然后再次用换行符替换字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2019-03-10
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多