使用 bash 脚本添加/删除 xml 标签 [英] Add/remove xml tags using a bash script

查看:18
本文介绍了使用 bash 脚本添加/删除 xml 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 xml 文件,我想使用 bash 脚本对其进行配置.例如,如果我有这个 xml:

I have an xml file that I want to configure using a bash script. For example if I had this xml:

<a>

  <b>
    <bb>
        <yyy>
            Bla 
        </yyy>
    </bb>
  </b>

  <c>
    <cc>
      Something
    </cc>
  </c>

  <d>
    bla
  </d>
</a>

(已删除机密信息)

我想编写一个 bash 脚本,该脚本将删除 <b> 部分(或对其进行注释),但保持 xml 的其余部分完整无缺.我对整个脚本编写很新.我想知道是否有人可以给我一个关于我应该调查什么的提示.

I would like to write a bash script that will remove section <b> (or comment it) but keep the rest of the xml intact. I am pretty new the the whole scripting thing. I was wondering if anyone could give me a hint as to what I should look into.

我认为可以使用 sed 除了 sed 是行编辑器.我认为删除 <b> 标签很容易,但是我不确定 sed 是否能够删除 之间的所有文本; 标签.

I was thinking that sed could be used except sed is a line editor. I think it would be easy to remove the <b> tags however I am unsure if sed would be able to remove all the text between the <b> tags.

我还需要编写一个脚本来重新添加已删除的部分.

I will also need to write a script to add back the deleted section.

推荐答案

这在 sed 中不难做到,因为 sed 也适用于范围.

This would not be difficult to do in sed, as sed also works on ranges.

试试这个(假设 xml 在一个名为 foo.xml 的文件中):

Try this (assuming xml is in a file named foo.xml):

sed -i '/<b>/,/</b>/d' foo.xml

-i 将更改写入原始文件(使用 -i.bak 保留原始文件的备份副本)

-i will write the change into the original file (use -i.bak to keep a backup copy of the original)

此 sed 命令将对范围指定的所有行执行操作 d(删除)

This sed command will perform an action d (delete) on all of the lines specified by the range

# all of the lines between a line that matches <b>
# and the next line that matches </b>, inclusive
/<b>/,/</b>/

所以,用简单的英语,这个命令将删除带有 <b> 的行之间和包括行之间的所有行.以及带有 </b>

So, in plain English, this command will delete all of the lines between and including the line with <b> and the line with </b>

如果您想注释掉这些行,请尝试以下方法之一:

If you'd rather comment out the lines, try one of these:

# block comment
sed -i 's/<b>/<!-- <b>/; s/</b>/</b> -->/' foo.xml

# comment out every line in the range
sed -i '/<b>/,/</b>/s/.*/<!-- & -->/' foo.xml

这篇关于使用 bash 脚本添加/删除 xml 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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