2010-04-05 81 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