Posted on 2010-01-22 16:52
Prayer 閱讀(591)
評論(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的所有行前面和下面都輸出一個空行