sed进阶

Posted ch122633

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sed进阶相关的知识,希望对你有一定的参考价值。

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

一、多行命令

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/
/ / } 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
Administrators 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 Users group meeting will be held.
All Desktop Users should attend.
Thank you for your attendance.
N使用例子

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

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

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

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

 

二、保持空间

 

三、排除命令

 

四、改变流

 

五、模式替代

 

六、在脚本中使用sed

 

七、创建sed实用工具

以上是关于sed进阶的主要内容,如果未能解决你的问题,请参考以下文章