2017-04-11 103 views
0

我有一个XML文件,file.xmlSED,AWK替换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 

值要搜索

01 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的方式,因为我可能会使用错误的工具,为任务?

+5

使用支持XML的工具。 'Sed'或'awk'不适合这项工作。 – choroba

+1

您可以使用'sed's/\ b500 \ b/600/g'file.xml'来替换500而不是5000. –

+0

快速搜索返回这种东西:http://stackoverflow.com/q/6523886/2088135 –

回答

0

sed可能是错误的工具,然而,如果它是某些没有其他的那些fileA.txt数字的file.xml存在,但是那些被改变,这应该工作:

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 -,运行这些命令。

0

你可以用xmlstarlet这样做。例如,

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

将取代30.00价格与32.00在您的示例文件中的价格。你可以从文件中构建一个命令行,如agc所示,但这会很麻烦。