2012-08-31 101 views
1

我正在嘗試僅使用Linux CLI工具處理XML文件。 ,我試圖解決的主要問題是對一個特定的XML標籤的內容複製到一個新的標籤,就像這樣:將XML標記的內容複製到一組新的XML標記中

<date>Wednesday</date> 
<name>The Name</name> 
<anotherattribute>Attribute</anotherattribute> 

到:

<date>Wednesday</date> 
<id>The Name</id> 
<name>The Name</name> 
<anotherattribute>Attribute</anotherattribute> 

我一直在嘗試使用sed的解決了這個問題,並且已經能夠識別標籤,並將其複製到保持緩衝器:

/<name>/{ 
h 
i\ 
<id> 
G 
a\ 
</id> 
} 

但其結果是:

<date>Wednesday</date> 
<id> 
<name>The Name</name> 
<name>The Name</name> 
</id> 
<anotherattribute>Attribute</anotherattribute> 

任何幫助,非常感謝。

+0

使用'sed'這種方式是一個非常糟糕的主意。不像嘗試用正則表達式解析HTML一樣糟糕,但仍然非常糟糕。看看這個問題的第二個答案:http://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash –

回答

1

試試這個:

sed '/<name>/{h;s/name>/id>/g;G}' 

您也可以嘗試xmlstarlet

cat input.xml | 
    xmlstarlet ed -i //name -t elem -n id -v '' | 
     xmlstarlet ed -u //id -x '../name'