1 保留空间
模式空间是一个活动的缓冲区,它在sed编辑器处理命令是保留被检查的文本。然而,它不是存储文本的唯一可用空间,sed编辑器利用一个成为保留空间的缓冲区。在处理模式空间中的其他行时,可以使用保留空间暂时保留文本呢行。有5个命令与使用保留空间有关。
命令:
h 将模式空间复制到保留空间
H 将模式空间追加到保留空间
g 将保留空间复制到模式空间
G 将保留空间追加到模式空间
x 将模式空间和保留空间的内容进行交换
这些命令可以用于将文本从模式空间复制到保留空间,其目的是腾空模式空间以载入其他字符串进行处理
通常使用h或H命令移动字符串到保留空间后,最终都会使用g.G,或x命令将保存的字符串移动到模式空间(否则也不必费心将他们保存起来)
使用两个缓冲区时,判断文本行处于哪个缓冲区容易产生混淆。
eg:
root@jiangjian-K42JZ:/home/jiangjian/sh# cat data
This is the header line
This is the first data line
This is the second data line
This is the last line
root@jiangjian-K42JZ:/home/jiangjian/sh# sed -n '/first/{
h #将模式空间复制到保留空间 现在保留区为This is the first data line
p #打印当前的模式空间
n #到下一行
p #会打印This si the frist data line 下面一行的内容This is the second data line
g # 将保留空间复制到模式空间 现在模式空间变为This is the first data line
p #将会输出模式空间的内容,经过上面的步骤,此时应该输出This is the first data line
}' data
This is the frist data line
This is the second data line
This is the first data line
root@jiangjian-K42JZ:/home/jiangjian/sh
可以使用这个功能实现的文本的反转
2 否定命令
感叹号(!)命令用于否定命令,他的意思是在通常命令被激活的地方不激活命令
root@jiangjian-K42JZ:/home/jiangjian/sh# cat data
This is the header line
This is the frist data line
This is the second data line
This is the last line
root@jiangjian-K42JZ:/home/jiangjian/sh# sed -n '/header/!p' data
This is the frist data line
This is the second data line
This is the last line
root@jiangjian-K42JZ:/home/jiangjian/sh#
针对上一篇当中当N读取最后一行时会停止工作,这里!可以很好的解决这个问题
root@jiangjian-K42JZ:/home/jiangjian/sh# cat data3
The frist meeting of the Linux System
Administrator's group will be held on Tuesday.
All System Administrators should attend this meeting.
root@jiangjian-K42JZ:/home/jiangjian/sh# sed '{
!N
s/System.Administrator/Desktop User/
}' data3
The frist meeting of the Linux System
Administrator's group will be held on Tuesday.
All Desktop Users should attend this meeting.
root@jiangjian-K42JZ:/home/jiangjian/sh#
root@jiangjian-K42JZ:/home/jiangjian/sh# cat data
This is the header line
This is the frist data line
This is the second data line
This is the last line
root@jiangjian-K42JZ:/home/jiangjian/sh# sed -n '{
> 1!G
> h
> p
> }' data
This is the header line
This is the frist data line
This is the header line
This is the second data line
This is the frist data line
This is the header line
This is the last line
This is the second data line
This is the frist data line
This is the header line
root@jiangjian-K42JZ:/home/jiangjian/sh#