且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Sed 正则表达式多行 - 替换 HTML

更新时间:2023-02-17 22:26:52

虽然@nhahtdh 的答案是您最初问题的正确答案,但此解决方案是您评论的答案:

While @nhahtdh's answer is the correct one for your original question, this solution is the answer to your comments:

sed '
  /<!-- PAGE TAG -->/,/<!-- PAGE TAG -->/ {
    1 {
      s/^.*$/Replace Data/
      b
    }
    d
  }
'

你可以这样读:

//,/<!-- PAGE TAG -->/ -> 用于这些正则表达式之间的行

/<!-- PAGE TAG -->/,/<!-- PAGE TAG -->/ -> for the lines between these regexes

1 { -> 第一个匹配行

s/^.*$/Replace Data/ -> 搜索任何内容并替换为 Replace Data

s/^.*$/Replace Data/ -> search for anything and replace with Replace Data

b -> 分支到结束(在这种情况下表现得像中断)

b -> branch to end (behaves like break in this instance)

d -> 否则,删除该行

d -> otherwise, delete the line

您可以通过在每个命令后添加分号将任何一系列 sed 命令与 gnu sed 合并为一行(但如果您希望以后能够阅读,则不建议这样做):

You can make any series of sed commands into one-liners with gnu sed by adding semicolons after each command (but it's not recommended if you want to be able to read it later on):

sed '/<!-- PAGE TAG -->/,/<!-- PAGE TAG -->/ { 1 { s/^.*$/Replace Data/; b; }; d; };'

顺便说一句,您真的应该在您的帖子中尽可能具体.替换/删除"是指替换或删除".如果要更换,就说更换.这对我们这些试图回答您的问题的人以及可能遇到相同问题的未来用户都有帮助.


Just as a side note, you should really try to be as specific as possible in your posting. "replaced/removed" means "replaced OR removed". If you want it replaced, just say replaced. That helps both those of us trying to answer your question and future users who might be experiencing the same issue.