【发布时间】:2017-09-06 20:24:42
【问题描述】:
我有一个 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>
从中,我需要将 fileA.txt 中的所有值替换为 fileB.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 脚本?
就像在 cmets 中一样,你能告诉我一个 python 方法吗,因为我可能使用了错误的工具来完成这项任务?
【问题讨论】:
-
使用可识别 XML 的工具。
Sed或awk不是适合这项工作的工具。 -
您可以使用
sed 's/\b500\b/600/g' file.xml仅替换 500 而不是 5000。 -
快速搜索返回这种东西:stackoverflow.com/q/6523886/2088135
-
不错的文件样本。 xml 文件中没有一个匹配项。祝你好运。