Chinaunix

标题: sed手册的一个范例 [打印本页]

作者: ccsjx    时间: 2010-06-15 22:35
标题: sed手册的一个范例
sed '/^$/{N;/^$/D}' urfile

作用是將文件內連續的空白行 , 刪除它們成為一行。

我将代码在linux上试了下,文本没变化。

范例错了吗?我按照上面的说明去理解觉得没问题啊。

高手们,错了的话,按这个思路应该怎么修改?

[sjx@localhost c_soure]$ cat s8
123
456

789

qwe





asd
[sjx@localhost c_soure]$ sed '/^$/{N;/^$/D}' s8
123
456

789

qwe





asd
[sjx@localhost c_soure]$
作者: Shell_HAT    时间: 2010-06-15 23:05
sed '/^$/{N;/^\n$/D}' urfile

你是不是少看了一点东西?
作者: ccsjx    时间: 2010-06-15 23:11
你是不是少看了一点东西?
Shell_HAT 发表于 2010-06-15 23:05



    没有,书上千真万确这么写的
    高手你一改我明白了,谢谢啊
作者: ccsjx    时间: 2010-06-15 23:15
本帖最后由 ccsjx 于 2010-06-15 23:20 编辑

/^\n$/D
这个的意思是检查pattern space内是否存在一行只有换行符的情况,有的话删除pattern space内第一行
也就是D前面的定位对象是整个pattern space。加\n是因为N添加下一行资料会在资料前面加上\n

这样理解对吗
作者: bbgg1983    时间: 2010-06-15 23:23

这几天学习论坛学习sed的热情高涨阿
作者: ccsjx    时间: 2010-06-15 23:24
回复 5# bbgg1983


    初学者,发现不懂得太多了,只能在论坛多多请教了
作者: Shell_HAT    时间: 2010-06-15 23:24
回复 4# ccsjx


很好,很正确。
作者: ccsjx    时间: 2010-06-15 23:31
回复 7# Shell_HAT


    /^\n$/D 定位的是pattern space内所有内容还是最后一行也就是N添加的那一行,感觉在这块我还是存在盲点。
   然后取行是否是像数据库那样存在一个cursor,执行N和从外部取行一样导致cursor的移动
作者: Shell_HAT    时间: 2010-06-15 23:38
回复 8# ccsjx


整个模式空间。man里面的说明是否可以帮助理解?
       D      Delete up to the first embedded newline in the pattern space.  Start next cycle, but skip reading from  the  input
              if there is still data in the pattern space.

作者: ccsjx    时间: 2010-06-15 23:54
回复 9# Shell_HAT


    整个模式空间的话:
   当碰上2个空行的情况:
   123
     空行
   空行
   456

     读入第一个空行,然后执行N,模式空间内为:
    空行\n空行
    然后执行D,删除第一行
    模式空间内为:空行还是\n空行?(也就是 Delete up to the first embedded newline in the pattern space包括\n吗)
    接着再执行D,模式空间内为空行\n456的话才准确

     所以D删除第一行的话包括了\n
作者: laohuanggua    时间: 2010-06-16 06:00
马克 一下。
作者: expert1    时间: 2010-06-16 13:44
D      Delete up to the first embedded newline in the pattern space.  Start next cycle, but skip reading from  the  input
              if there is still data in the pattern space.



这里 but skip reading from  the  input
              if there is still data in the pattern space.

是么意思呢?好像没什么用?
作者: Shell_HAT    时间: 2010-06-16 14:42
回复 12# expert1


合并连续空行的例子里面用它来删掉多余的\n
作者: expert1    时间: 2010-06-16 15:49
本帖最后由 expert1 于 2010-06-16 16:48 编辑

明白了,当pattern space还有数据的时候,此时不再接受读入。此时的N没有任何作用了。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2