2015-11-04 37 views
-1

我試圖消除< ..>標記了這個小腳本(它的名字是test):修改腳本與sep。不一致的行爲

<chan‌​ges><comment>Testing 

Comment 

Footer 
</comment></chan‌​ges> 

Whevener我嘗試用cat test | sed -e "s/<\/comment>//g; s/<comment>/ /g" > test1

輸出是正確的:

<chan‌​ges> Testing 

Comment 

Footer 
</chan‌​ges> 

但是,當我嘗試cat test | sed -e "s/<\/changes>//g; s/<changes>/ /g" > test1時,腳本保持不變。

我在shell上覆制/粘貼每一個命令並在把它放到這裏之前進行了測試,所以我相信這不是錯別字的問題。

任何人都知道這是什麼樣的黑魔法?

+0

你的'changes'文本中有一些奇怪的字符。如果我複製它,我會看到'chan <200c><200b> ges'。 – fedorqui

+0

看起來像XML。它是XML嗎?因爲如果是這樣,你應該使用解析器。 – Sobrique

回答

1

假如你想轉換:

<chan‌​ges><comment>Testing 

Comment 

Footer 
</comment></chan‌​ges> 

要:

<chan‌​ges>Testing 

Comment 

Footer 
</chan‌​ges> 

您可以使用(?:<(comment)>)(.*)(?:<\/\1>)和替換\2 https://regex101.com/r/rC1rP6/1

編輯:簡單的正則表達式和sed例子:

cat test | sed 's/<\/\?comment>//g 

更換commentchan‌​ges搭配其它應答器。

注意:你失敗的原因是因爲changes與一個Unicode字符寫入:

  • cat test | xxd顯示:

    0000000: 3c63 6861 6ee2 808c e280 8b67 6573 3e3c <chan......ges>< 
    
  • echo '<changes>' | xxd顯示:

    0000000: 3c63 6861 6e67 6573 3e0a     <changes>. 
    
+1

我知道有很多可能性來改善正則表達式,但我想要的是刪除'',''和''已被替換爲當前命令。不過,正則表達式工具非常棒。感謝那 –

+0

看到我的編輯和解釋。 – Cyrbil

+0

你說得對,原文是用unicode編寫的。 +1解釋如何看到這一點。 –

0

我認爲正確的工具是而不是是一個正則表達式。因爲正則表達式在標籤匹配方面不是很擅長。我反而建議使用一個分析器 - 這是一個Perl的片段,會做你需要什麼:

#!/usr/bin/env perl 

use strict; 
use warnings; 

use XML::Twig; 

print XML::Twig -> parse (\*DATA) -> get_xpath('//*',0) -> text; 

__DATA__ 
<changes><comment>Testing 

Comment 

Footer 
</comment></changes> 

NB - 不得不清理源數據,其中有一些奇怪的字符,當我複製和粘貼,這可能實際上是你的問題的根源。

這你可以將一個內襯爲:

perl -MXML::Twig -0777 'print XML::Twig->parse(<>)->get_xpath('//*',0)->text;' you_xml_filename 

(或者它會接受管道輸入)。

對於更復雜的情況下,這將無法正常工作非常好,但它是非常容易的,以適應更廣泛的標籤剝離:

如:

#!/usr/bin/env perl 

use strict; 
use warnings; 

use XML::Twig; 

print map { $_ -> text } XML::Twig -> parse (\*DATA) -> get_xpath('//#PCDATA'); 

__DATA__ 
<changes><comment>Testing 

Comment 

Footer 
</comment> 
<anothercomment>fish here 
</anothercomment> 
<some_other_tag an_attribute="some_attribute">More text here</some_other_tag> 
</changes> 

XML::Twig可能需要在安裝這應該和cpan XML::Twig一樣簡單,或者使用你的包管理器)