【问题标题】:Find and Replace HTML tag using SED in Shell在 Shell 中使用 SED 查找和替换 HTML 标记
【发布时间】:2014-12-03 08:05:26
【问题描述】:

我想要实现的是,使用 Shell 脚本将 html 标记替换为文件中的修改标记。当我使用 Shell 搜索查找和替换时,我开始了解 SED。我尝试了我的目的,但它抛出了错误。我的代码是,

pattern='<html style=background-color:#ffffff;>'
replacement='<html style=background-color:#ffffff; manifest="app.appcache">'

cat "index.html"  | sed "/s/$pattern/$replacement/" > "index2.html"

我收到以下错误,

sed: 1: "/s/<html style=backgrou ...": invalid command code <

从其他几个stackoverflow问题中,我尝试不使用

pattern='<html style=background-color:#ffffff;>'
replacement='<html style=background-color:#ffffff; manifest="app.appcache">'

sed "/s/$pattern/$replacement/" <"index.html" >"index2.html"

我遇到了同样的错误。

请帮助我如何做到这一点。

【问题讨论】:

    标签: regex linux bash shell sed


    【解决方案1】:

    试试

    #    v-- no leading slash
    sed "s/$pattern/$replacement/" index.html > index2.html
    

    【讨论】:

      【解决方案2】:

      应该这样做:

      pattern="<html style=background-color:#ffffff;>"
      replacement="<html style=background-color:#ffffff; manifest=\"app.appcache\">"
      
      sed "s/$pattern/$replacement/g" index.html > index2.html
      

      【讨论】:

      • 如果将模式周围的's 替换为"s,则模式内的"s 将被shell 丢弃。
      【解决方案3】:

      感谢您的回答, 它与我从博客中获得的“@”一起使用

      sed -e 's@<html style=background-color:#ffffff;>@<html style=background-color:#ffffff; manifest="app.appcache">@g' <"index.html" >"index2.html"
      

      【讨论】:

      • 错误不是@。看看温特穆特的回答。唯一的问题是前导斜线。
      猜你喜欢
      • 2020-08-05
      • 1970-01-01
      • 2017-05-14
      • 2021-10-06
      • 1970-01-01
      • 2019-11-29
      • 2014-02-11
      • 2021-09-30
      • 2018-10-01
      相关资源
      最近更新 更多