2017-04-11 101 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所示,但這會很麻煩。