【问题标题】:sed insert/append and printing pattern spacesed 插入/追加和打印模式空间
【发布时间】:2013-09-10 16:36:58
【问题描述】:

我想操作一个文本文件,以便将缩进的行块用 {{{ 和 }}} 括起来。

这是我卡住的地方:

  1 /^\ [^\ ]/,/^[^\ ]/{        # match range: all indented plus line after that
  2    b fixIndented            # branch
  3 }
  4 
  5 /^[^\ ]/{p;b}               # print all non-indented outside range and exit.
  6                             
  7 :fixIndented
  8 /^[^\ ]/{                   # match last line of range
  9    x;                       # swap Holdbuffer und patternSpace, edit patternSpace
 10    i\
 11       {{{
 12    a\
 13       }}}
 14    p;
 15    x;p;
 16 }
 17 H;                          # write each line in range into holdBuffer

我认为第 15 行应该在保持缓冲区中读取(包含我在第 9 行中交换的内容)然后打印它,打印操作模式空间(第 10-13 行)之后( 14)。 但这不会发生。相反,它似乎将保持缓冲区中的行合并到模式空间中。像这样:

bla
blubb
 foo1
 bla2
 foo3
sadgfasdf
bar
foo

变成:

bla
blubb
      {{{

 foo1
 bla2
 foo3
sadgfasdf
      }}}   
bar
foo

如果有人花时间为我指明正确的方向,我将不胜感激。谢谢,

【问题讨论】:

  • +1 提出有趣问题的好问题。 .....但是除非您“嫁给” sed,否则 awk 将是解决此问题的一个更容易的方法。祝你好运
  • 有趣!好的练习。让我们试试吧!

标签: regex awk sed


【解决方案1】:

sed 也可以,但是 awk 就简单多了:

cat file
bla
blubb
 foo1
 bla2
 foo3
sadgfasdf
bar
foo

awk '!s && /^ /{s=1; $0 = " {{{" ORS $0} s && /^[^ ]/{s=0; $0 = " }}}" ORS $0}1' file
bla
blubb
 {{{
 foo1
 bla2
 foo3
 }}}
sadgfasdf
bar
foo

【讨论】:

  • @michaelP:我告诉过你这会更容易; -) 祝大家好运。
  • 这样就解决了问题,非常感谢!明天在工作中我必须检查它如何与更大的环境融合(也就是说,看看缩进的大括号是否会成为问题),但它是一个令人印象深刻的单线,做我想要的! @shellter:不,我没有和 sed 结婚,看到 awk 解决这个问题是多么容易,我现在肯定会考虑提出离婚 :)
猜你喜欢
  • 2015-03-05
  • 1970-01-01
  • 2023-03-25
  • 2018-11-21
  • 1970-01-01
  • 2014-12-15
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多