2010-04-05 61 views
0

我有一個sed命令註釋掉XML命令桑達:正則表達式匹配線而不< -

sed 's/^\([ \t]*\)\(.*[0-9a-zA-Z<].*\)$/\1<!-- Security: \2 -->/' web.xml 

注意到:

<a> 

    <!-- Comment --> 
    <b> 
    bla 
    </b> 

</a> 

產地:

<!-- Security: <a> --> 

    <!-- Security: <!-- Comment --> --> // NOTE: there are two end comments. 
    <!-- Security: <b> --> 
    <!-- Security: bla --> 
    <!-- Security: </b> --> 

<!-- Security: </a> --> 

理想我不想用我的sed腳本來評論已經評論過的東西。

即:

<!-- Security: <a> --> 

    <!-- Comment --> 
    <!-- Security: <b> --> 
    <!-- Security: bla --> 
    <!-- Security: </b> --> 

<!-- Security: </a> --> 

我可以做這樣的事情:

sed 's/^\([ \t]*\)\(.*[0-9a-zA-Z<].*\)$/\1<!-- Security: \2 -->/' web.xml 
sed 's/^[ \t]*<!-- Security: \(<!--.*-->\) -->/\1/' web.xml 

,但我覺得一個襯墊清潔

這是非常相似的(?):matching a line that doesn't contain specific text with regular expressions

回答

1

結束了這是怎麼回事:

startInsert="<!-- Security: " 
endInsert=" -->" 

whiteSpace="[ \t]*" 
char="[0-9a-zA-Z^_)!-/:[email protected][-\{-~]" 

sed "s/^\($whiteSpace\)\(.*$char.*\)$/\1$startInsert\2$endInsert/" $file 
sed "s/^\($whiteSpace\)$startInsert\(<!--.*\-->\)$endInsert/\1\2/" $file 

不一樣舉止優雅,我所期待的,但就像一個魅力。

2

這似乎工作。

^([ \t]*)(?!<!--)([0-9a-zA-Z<].*)$ 

你必須逃離parenteses和其他的東西實際上爲了使其與sed的工作。

已測試在線regular expression tester中的表達式。

不幸的是,似乎sed不支持lookahead(但是sseddoes)。
你應該嘗試awkssed

+0

是的,我已經嘗試過(和不同的變化),但我無法得到它的工作。它最終沒有突出顯示。 – sixtyfootersdude 2010-04-05 18:17:42

+0

進一步閱讀後,似乎sed不支持這些表達式。你必須使用ssed和活動perl模式(-R)。發現這裏的信息:http://sed.sourceforge.net/sedfaq6.html – 2010-04-06 17:27:38

+0

Coool。這也是我的想法。 +1澄清 – sixtyfootersdude 2010-04-06 19:50:16

1

您可以用awk,如果我得到你的要求正確:

awk -F"," '!/<!--/&&NF{$0="<!-- Security: "$0"-->"}1' file 
+0

嗯,真的寧願使用sed,但建議+1。 – sixtyfootersdude 2010-04-07 19:56:17