+ -
当前位置:首页 → 问答吧 → sed完成跨行匹配的问题

sed完成跨行匹配的问题

时间:2011-07-04

来源:互联网

现在想用sed完成类似grep打印匹配字符串的行,grep只能打印单行匹配字符串的行,现在匹配字符串跨两行了,用sed怎么实现,具体说明代码如下:
  1. #cat cul
  2. n1thing nothing
  3. n2thing cat and dog
  4. n3thing nothing
  5. n4thing cat and
  6. dog n5thing
  7. n6thing nothing
复制代码
这个是要处理的文本,将要匹配的字符串是cat and dog,用数字替换nothing的o是为了表明行号,以免混乱了。
可以看到第二行可以匹配cat and dog  , 第四,五行也是匹配的,现在要用sed实现打印匹配的行,打印结果如下:
  1. n2thing cat and dog
  2. n4thing cat and
  3. dog n5thing
复制代码
如何用sed实现这个功能呢???

作者: jack1007   发布时间: 2011-07-04

曾经有个帖子。。。搜索一下

作者: bbgg1983   发布时间: 2011-07-04

作者: bbgg1983   发布时间: 2011-07-04

晕菜,还真是看到一个地方去了,呵呵,我就是想有没有人能写出不一样的出来,呵呵
下面是我把书上脚本换成命令行的模式,还有纠正那个bug  $!N
  1. #sed '/cat and dog/b;$!N;h;s/.*\n//;/cat and dog/b;g;s/ *\n/ /;/cat and dog/{g;b};g;D' cul
  2. n2thing cat and dog
  3. n4thing cat and
  4. dog n5thing
复制代码
看看有没有高手写出不一样的来。

作者: jack1007   发布时间: 2011-07-04

好贴……

作者: xiaopan3322   发布时间: 2011-07-04