2012-11-15 68 views
0

請幫忙! 我不得不花費大量時間尋找我的resoultion,和我打我的頭在牆上... 所有我想用SED做的是: 查找標籤,其中包含「號將其刪除」的字符串,並將其取出不包括sed中的xml標記 - 特定情況下

輸入:

<Cell ss:StyleID="s128"/> 
    <Cell ss:StyleID="s128"/> 
    </Row> 
    <Row ss:AutoFitHeight="0"> 
    <Cell ss:StyleID="s81"><Data ss:Type="String">Number Deleted</Data></Cell> 
    <Cell ss:StyleID="s81"/> 
    <Cell ss:StyleID="s81"/> 
    <Cell ss:StyleID="s81"/> 
    <Cell ss:StyleID="s82"><Data ss:Type="Boolean">0</Data></Cell> 
    <Cell ss:StyleID="s81"/> 
    <Cell ss:StyleID="s82"><Data ss:Type="Boolean">0</Data></Cell> 
    <Cell ss:StyleID="s83"><Data ss:Type="String">-1</Data></Cell> 
    <Cell ss:StyleID="s81"><Data ss:Type="String">&quot;Deleted:&quot;</Data></Cell> 
    <Cell ss:StyleID="s81"/> 
    <Cell ss:StyleID="s81"/> 
    <Cell ss:StyleID="s81"/> 
    </Row> 
    <Row ss:AutoFitHeight="0"> 
    <Cell><Data ss:Type="String">Number Saved</Data></Cell> 
    <Cell ss:Index="5"><Data ss:Type="Boolean">0</Data></Cell> 
    <Cell ss:Index="7"><Data ss:Type="Boolean">0</Data></Cell> 

輸出:

<Cell ss:StyleID="s128"/> 
    <Cell ss:StyleID="s128"/> 
    </Row> 

    <Row ss:AutoFitHeight="0"> 
    <Cell><Data ss:Type="String">Number Saved</Data></Cell> 
    <Cell ss:Index="5"><Data ss:Type="Boolean">0</Data></Cell> 
    <Cell ss:Index="7"><Data ss:Type="Boolean">0</Data></Cell> 

到目前爲止,我想通了,如何查看XML exluding從「號碼刪除」行,直到標籤的結束,但是這確實錯了XML的完整性,因爲標籤是沒有關閉,這裏是我的:

function filter_xml 
{ 
    START="<Cell ss:StyleID="s81"><Data ss:Type="String">Number Deleted" 
    END="<\/Row>" 
    sed "/$START/,/$END/d" file.xml 
} 
+1

你應該使用XML工具進行這種類型的操作。使用sed或grep將會在任何複雜的嵌套上失敗。 –

+0

肯定的事情,該sed是不合適的,但殺了我:)它必須是sed – pawel3ala

回答

1

使用XML-aware工具。例如,xsh

open file.xml ; 
remove //Row[Cell/Data/text()='Number Deleted'] ; 
save :b ; 
1

我不認爲sed是用於處理XML文件的最佳工具。

難道你不能真正解析XML文件嗎?

這裏是一個一些快速和骯髒例如用python

在/ tmp /數據文件:

<data xmlns:ss="foobar"> 
<Row> 
<Cell ss:StyleID="s128"/> 
<Cell ss:StyleID="s128"/> 
</Row> 
<Row ss:AutoFitHeight="0"> 
<Cell ss:StyleID="s81"><Data ss:Type="String">Number Deleted</Data></Cell> 
<Cell ss:StyleID="s83"><Data ss:Type="String">-1</Data></Cell> 
</Row> 
<Row ss:AutoFitHeight="0"> 
<Cell><Data ss:Type="String">Number Saved</Data></Cell> 
<Cell ss:Index="5"><Data ss:Type="Boolean">0</Data></Cell> 
</Row> 
</data> 

Python代碼:

import xml.dom.minidom as Xml 
file = "/tmp/data" 
xmlDoc = Xml.parse(file) 
for row in xmlDoc.getElementsByTagName("Row"): 
    if "Number Deleted" not in row.toprettyxml(): 
    print row.toxml() 

輸出:

<Row> 
<Cell ss:StyleID="s128"/> 
<Cell ss:StyleID="s128"/> 
</Row> 
<Row ss:AutoFitHeight="0"> 
<Cell><Data ss:Type="String">Number Saved</Data></Cell> 
<Cell ss:Index="5"><Data ss:Type="Boolean">0</Data></Cell> 
</Row> 
0

這可能爲你工作(GNU SED):

sed '/<Row /!b;:a;$bb;N;/.*\n[^\n]*<\/Row>/!ba;:b;/Number Deleted/d' file