繁体   English   中英

sed,awk替换xml元素

[英]sed, awk to replace xml elements

我有一个xml文件,file.xml

如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

从中,我需要用在fileB.txt中找到的值替换在fileA.txt中找到的所有值。

fileA.txt的示例:

500
345
623
etc

要搜索的值

fileB.txt的示例:

550
350
700
etc

所以<price>500</price>应该变成<price>550</price>

我可以多次运行以下命令,

sed -i 's/old/new/g' file.xml,

您能告诉我一种更聪明的方法吗,例如指定替换只能在标签中进行,并且如果我需要用600替换500,那么5000不会变成6000?

也许会首选python脚本?

如评论中所述,由于我可能使用了错误的工具来执行任务,因此您可以向我展示python方式吗?

sed可能是错误的工具,但是如果可以确定 file.xml中没有其他fileA.txt号,但可以更改,则应该可以:

paste file[AB].txt | sed 's/^.*/s#\\b&/;s/.*$/&#g/;s/\t/\\b#/' | sed -f - file.xml

首先pastefileA.txtfileB.txt放在一起:

500 550
345 350
623 700
etc etc

然后sed即到未来的转换sed 小号 ubstitute命令:

s#\b500\b#550#g
s#\b345\b#350#g
s#\b623\b#700#g
s#\betc\b#etc#g

之后,将它们通过管道传递给sed -f - ,后者将运行这些命令。

您可以使用xmlstarlet执行类似的xmlstarlet 例如,

xmlstarlet ed -u //price[text()='30.00'] -v '32.00' bookstore.xml

将示例文件中的价格32.00替换为价格30.00 您可以按照agc的说明从文件构建命令行,但这会很麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM