2013-07-18 49 views
5

我有一个文本正文,其中包含使用<>,##或||分隔的组。 块从未重叠,但也可以跨越多行,像这样:替换sed中的多个分隔块

#A fully emphasized line# 
A line with #emphasis inside#. 
#Several lines of 
text 
With emphasis# 
no emphasis 
Line #with# multiple #emphasis#. 
Line <with some > |text of| #each type#. 

我试图与[和] 放后]最终定界符来替换每对分隔符;例如最后一行应该是:

Line [with some ]> [text of]| [each type]#. 

我已经形成了sed脚本将做的第一部分:

sed -e ':left s/[#|<]/[/; t right; n; b left :right s/[#|>]/]/; t left;n; b right' 

但是当我尝试使用&(或(..) + \ 1)把字符回这样的:

sed -e ':left s/[#|<]/[/; t right; n; b left :right s/[#|>]/]&/; t left;n; b right' 

我得到如下:

[A fully emphasized line][ 
A line with ][emphasis inside][. 
][Several lines of 
text 
With emphasis][ 
no emphasis 
Line ][with][ multiple ][emphasis][. 
Line [with some ]]]]]]> [text of[ [each type[. 

虽然我不确定这里出了什么问题,但它似乎是以某种方式与图案块混在一起。我可以用三个调用(每个匹配类型一个硬编码)替换它,但这似乎过分。

回答

4

请尝试以下命令。它读取内存中的整个文件,做每对分隔符的全球替代:

sed -e ' 
    :a 
    $! { N; ba }; 
    s/#\([^#]*\)#/[\1]#/g; 
    s/<\([^>]*\)>/[\1]>/g; 
    s/|\([^|]*\)|/[\1]|/g 
' infile 

它产生:

[A fully emphasized line]# 
A line with [emphasis inside]#. 
[Several lines of 
text 
With emphasis]# 
no emphasis 
Line [with]# multiple [emphasis]#. 
Line [with some ]> [text of]| [each type]#. 
+1

酷。合并版本也适用于此,所以三个搜索可以用's/[#|替换<]\([^#|>] * \)\([#|>]] \)/ [\ 1] \ 2/g;' –

+0

user2596375 - 三个sed表达式更好,因为您的模式取代了任何一对分隔符,例如,'#text>'将被'[text]>替换,即使它不是'#text#'。 – gbrener