Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

什么是sed的hold space 和pattern space

Posted on 2010-01-22 16:52 Prayer 阅读(571) 评论(1)  编辑 收藏 引用 所属分类: Shell
http://930699.k43.opensrs.cn/bbs/index.php?showtopic=744


$ cat foo
11111111111111
22222222222222
test33333333333333
44444444444444
55555555555555

$ sed '/test/{x;p;x;}' foo
11111111111111
22222222222222

test33333333333333
44444444444444
55555555555555


解释:
sed 中 x 的用法
The exchange function interchanges the contents of the pattern space and the holding area. The maximum number of addresses is two.
即交换保持空间hold space和模式空间pattern space的内容

sed 中 p 的作用是把模式空间复制到标准输出。

分析一下该命令执行过程中保持空间和模式空间的内容

命令 保持空间 模式空间
x 执行前:null 执行后:testn 执行前:testn 执行后:null
p 执行前:null 执行后:testn 执行前:testn 执行后:null 输出一个空行
x 执行前:testn 执行后:null 执行前:null 执行后:testn

(注:把test所在的行简写为test了)

引申:
可以试验一下 sed '/test/{x;p;}' foo 或者 sed '/test/{p;x;}' foo 等,看看结果,体会两个空间的变化

相应的:
sed '/regex/G' 是在匹配regex的所有行下面输出一个空行
sed '/regex/{x;p;x;G;}' 是在匹配regex的所有行前面和下面都输出一个空行

Feedback

# re: 什么是sed的hold space 和pattern space  回复  更多评论   

2010-02-04 23:20 by yzhkpli
p 执行前:null 执行后:testn 执行前:testn 执行后:null 输出一个空行
======================
这句不对吧?
p又不改变模式空间和匹配空间的内容。
应该是和x执行后一样的:
p 执行前:testn执行后:testn 执行前:null 执行后:null,
而p是输出pattern space的内容,所以打印一个空行!

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理