![](/img/trans.png)
[英]how to remove or replace specific chars are between two xml tags [linux, python, lxml, sed, awk,…]?
[英]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
首先paste
將fileA.txt和fileB.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.