SED
三、保持空间
- h/H hold,将模式空间的内容覆盖h(追加H)到保持空间
- G/g get,将保持空间内容覆盖g(追加G)到模式空间
- x exchange,交换两个空间的内容
- 举例
- 把多行用,拼接成一行
[root@localhost tmp]#sed 'H;${x;s/\n/,/g;s/^,//};$!d' test
- 将行反转输出
[root@localhost tmp]#sed '1!G;h;$!d' test22
[root@localhost tmp]#sed -n '1!G;h;$p' test22
理解
四、改变流
- 改变默认sed的工作流程(从头到尾执行脚本)
branch
无条件的跳转
用法
[address]b [label]
label定义
:LABEL
举例
test0311文件内容
This is the 0 header line.
This is the 100 first data line.
This is the 200 second data line.
This is the 300 last data line.
无条件跳转
[root@localhost tmp]#sed '2,3b;s/This is/Is this/;s/line./test?/' test0311
带标签的无条件跳转
[root@localhost tmp]#sed '/first/b jump1;s/This is/Is this/;:jump1;s/line./test?/' test0311
有条件的跳转
[root@localhost tmp]#echo "This, is , a, test, to, remove, coomas." | sed ':start;s/,//;t start'
- test
有条件跳转到指定标签
五、模式替代
- &
&同来替换正则匹配到的内容
例子
[root@localhost tmp]#sed -r 's/[0-9]+/&s/g' test0311
- \1(后向引用)
例子
[root@localhost tmp]#sed -r 's/(^.*)(\b[0-9]+\b )(.*$)/\2\1\3/g' test0311
[root@localhost tmp]#echo "abc 123 def" | sed -r 's/(^.*)(\b[0-9]+ \b)(.*$)/\2\1\3/g'
123 abc def
六、sed N将两行数据当成一行来处理
1.从字符串中删掉了换行符,导致两行合并成一行
[root@localhost tmp]#sed '/first/{ N; s/\n/ /}' test
2.替换字符
[root@localhost tmp]#sed 'N ; s/this is/Is this/ ' test