曲径通幽论坛

标题: 使用 g 命令将 hold space 中内容复制到 pattern space [打印本页]

作者: beyes    时间: 2012-2-3 11:29
标题: 使用 g 命令将 hold space 中内容复制到 pattern space
g 命令可以将 hold space 中内容复制到 pattern space。

供测试用的文本内容:
[root@qunet sed]# cat tmp.txt
#website
        groad.net
        baidu.com
        sina.com

#welcom
        hainan
        beijing
        jiangsu

#system
        unix
        linux
        windows
下面的例子将演示如果发现某匹配行就打印出其前一行,命令组中使用到了 g 命令,如下所示:
[root@qunet sed]# sed -n '/unix/{g;1!p};h' tmp.txt
#system
在上面的命令中,会一直试图寻找 unix 这个匹配,若是没有发生匹配,那么将执行 h 命令 ,将 pattern space 中的这行内容复制到 hold space 中。如果找到了匹配 unix 的行,那么就用 g 命令将之前在 hold space 中的内容复制回 pattern space,然后将其打印出来。这里需要注意一点,1!p 表示不是第一行就打印,也就是说,如果 unix 发生在第一行匹配,那么此时 hold space 中的内容为空,当空行复制到 pattern space 中时,将覆盖掉原先读入的第一行内容,而 1!p 自然也不会打印,最后再执行一个 h 命令也相当于做了一个无用的操作,最后的结果是了两个 space 中什么都没有,其等效于 sed 并没有开始工作。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2