sed高级命令
sed前面一些基础的命令只能针对单行进行操作,但是有的时候我们要处理
的并不只是一行;所以就需要使用一些高级命令。
- Next 命令(N):将数据流中的下一行加进来创建一个多行组来处理
- Delete(D):删除多行组中的一行。
- Print(P):打印多行组中的一行。
案例
追加下一行(N)
下面这个例子就是用sed 匹配到header这一行的内容,再使用N将匹配到内容和下一行加入到模式空间;然后使用替换命令将line. 和换行 转换成and;最后结果就是将两行转换为了一行。
[root@localhost ~]# cat 456 This is the header line. This is the first data line. This is the second data line. This is the last line. [root@localhost ~]# sed ' /header/{ N s/line.\n/and / }' 456 This is the header and This is the first data line. This is the second data line. This is the last line.
$!N
它是除了匹配到的最后一行不执行N命令,其他所有行都要执行N命令。
[root@localhost ~]# cat 456 This is the header line. This is the first data line. This is the second data line. This is the last line. This is and. [root@localhost ~]# sed ' /line./{ $!N s/\nThis/ and This/ }' 456 This is the header line. and This is the first data line. This is the second data line. and This is the last line. This is and.
多行删除(D)
它删除模式空间中直到第一个嵌入的换行符的这部分内容。它不会导致读入新的输入行。
[root@localhost ~]# cat abc See Section See Section See Section See Section See Section end [root@localhost ~]# sed ' > /^$/{ > N > /^\n$/d > }' abc See Section See Section See Section See Section See Section end [root@localhost ~]# sed ' /^$/{ N /^\n$/D }' abc See Section See Section See Section See Section See Section end
多行打印(P)
[root@localhost ~]# cat text Here are examples of the UNIX System. Where UNlX System appears,it should be the UNIX System appears,it should be the UNIX Operating System. [root@localhost ~]# sed ' /UNIX$/{ N /\nSystem/{ s/the/& Operating/ P D} }' text Here are examples of the Operating UNIX System. Where UNlX System appears,it should be the Operating UNIX System appears,it should be the UNIX Operating System.
保持空间最常的用途是,当改变模式空间中的原始内容时,用于保留当前输入行的副本。影响模式空间的命令有:
命令 | 缩写 | 功能 |
---|---|---|
Hold | h或H | 将模式空间的内容复制或追加到保持空间 |
Get | g或G | 将保持空间的内容复制或追加到模式空间 |
Exchange | x | 交换保持空间或模式空间的内容 |
[root@localhost ~]# cat 123 1 11 111 2 22 222 12 21 [root@localhost ~]# sed ' > /1/{ > h > d} > G' 123 2 111 22 111 222 111