Sed正则表达式多行-替换HTML [英] Sed regexp multiline - replace HTML

查看:435
本文介绍了Sed正则表达式多行-替换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 -->

我已经尝试并失败了!

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'

<!-- PAGE TAG -->之间的所有内容都应更换.

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 -->/->用于这些正则表达式之间的行

/<!-- 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->否则,删除该行

您可以通过在每条命令后添加分号来将任何系列的sed命令与gnu s组合成一个单行(但不建议您稍后再阅读):

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正则表达式多行-替换HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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