【问题标题】:Replacing multiple delimited blocks in sed替换 sed 中的多个分隔块
【发布时间】:2013-07-19 00:48:35
【问题描述】:

我有一段文本,其中包含用 、## 或 || 分隔的组。 这些块永远不会重叠,但可能会跨越多条线,如下所示:

#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[.

我不确定这里出了什么问题 - 它似乎以某种方式与模式块搞砸了。我可以用三个调用来替换它(每个匹配类型一个硬编码),但这似乎太过分了。

【问题讨论】:

    标签: sed


    【解决方案1】:

    尝试以下命令。它读取内存中的整个文件并对每对分隔符进行全局替换:

    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]#.
    

    【讨论】:

    • 酷。合并后的版本也适用于此,因此可以将三个搜索替换为:s/[#|&lt;]\([^#|&gt;]*\)\([#|&gt;]\)/[\1]\2/g;
    • user2596375 - 三个 sed 表达式更出色,因为您的模式替换了任何一对分隔符,不一定是匹配的分隔符。例如,#text&gt; 将被替换为 [text]&gt;,即使它不是 #text#
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2014-09-27
    • 2021-10-25
    • 1970-01-01
    • 2013-05-25
    • 2012-10-14
    相关资源
    最近更新 更多