Sed regexp 多行 - 替换 HTML [英] Sed regexp multiline - replace HTML

查看:31
本文介绍了Sed regexp 多行 - 替换 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Linux 系统上使用 sed 替换多行

I am attempting to replace multiple lines using sed on a Linux system

这是我的文件

<!-- PAGE TAG -->
DATA1
DATA2
DATA3
DATA4
DATA5
DATA6
<div id="DATA"></div>
DATA8
DATA9
<!-- PAGE TAG -->

我所做的尝试都失败了!

The attempts I have made and failed!

sed -n '1h;1!H;${;g;s/<!-- PAGE TAG -->.*<!-- PAGE TAG -->//g;p;}' 
sed -n '1!N; s/<!-- PAGE TAG -->.*<!-- PAGE TAG -->// p'
sed -i 's|<!--[^>]*-->[^+]+<!--[^>]*-->||g' 
sed -i 's|///<!-- PAGE TA -->/,///<!-- PAGE TA -->||g'

之间的所有内容都应该被替换.

Everything in between <!-- PAGE TAG --> should be replaced.

这个问题类似sed 多行替换

推荐答案

虽然@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 -->/ -> for the lines between these regexes

1 { -> 为第一个匹配行

1 { -> for the first matching line

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

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

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

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.

这篇关于Sed regexp 多行 - 替换 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆