首页 > 其他 > 详细

sed进阶

时间:2019-01-23 22:55:30      阅读:173      评论:0      收藏:0      [点我收藏+]

下面这些命令未必经常会用到,但当需要时,知道这些肯定是件好事。

一、多行命令

sed命令通常是对一行数据进行处理,然后下一行重复处理。

sed编辑器包含了三个可用来处理多行文本的特殊命令

  • N:将数据流中的下一行加进来创建一个多行组来处理
  • D:删除多行组中的一行
  • P:打印多行组中的一行

1.1 next命令

两种删除匹配的下一行的办法:

技术分享图片
cat data1.txt 
This is the header line.

This is a data line.

This is the last line.

sed ‘/^$/d‘ data1.txt 
This is the header line.
This is a data line.
This is the last line.

sed ‘/header/{n ; d}‘ data1.txt 
This is the header line.
This is a data line.

This is the last line.
空行处理

 

1.2 合并文本行

用大写N,可以一次性读取两行。区别与n是移动到下一行。

技术分享图片
$ sed ‘/first/{ N ; s/\n/ / }‘ data2.txt 
This is the header line.
This is the first data line. This is the second data line.
This is the last line.

$ cat data2.txt 
This is the header line.
This is the first data line.
This is the second data line.
This is the last line.

$ cat data3.txt 
On Tuesday, the Linux System
Administrator‘s group meeting will be held.
All System Administrators should attend.
Thank you for your attendance.

$ sed ‘N ; s/System.Administrator/Desktop User/‘ data3.txt
On Tuesday, the Linux Desktop User‘s group meeting will be held.
All Desktop Users should attend.
Thank you for your attendance.
N使用例子

在N后面最好匹配多行命令,而单行命令则可以放在N前面,如:

技术分享图片
$ sed ‘N
> s/System\nAdministrator/Desktop\nUser/
> s/System Administrator/Desktop User/
> ‘ data4.txt
On Tuesday, the Linux Desktop
User‘s group meeting will be held.
All System Administrators should attend.

$ cat data4.txt 
On Tuesday, the Linux System
Administrator‘s group meeting will be held.
All System Administrators should attend.

$ sed ‘
> s/System Administrator/Desktop User/
> N
> s/System\nAdministrator/Desktop\nUser/
> ‘ data4.txt
On Tuesday, the Linux Desktop
User‘s group meeting will be held.
All Desktop Users should attend.
前后写的例子

 

二、保持空间

 

三、排除命令

 

四、改变流

 

五、模式替代

 

六、在脚本中使用sed

 

七、创建sed实用工具

sed进阶

原文:https://www.cnblogs.com/ch122633/p/10311935.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!