玩玩sed -- pattern space和hold space
sed的工作原理:
file
+----------+
| line1 |
|----------| pattern space
| ... | input +--------------+ output
| linek |-------> sed | linek | --------> linej (the result of processing linek)
|----------| +--------------+
| linex | | |
+----------+ +--------------+
hold space
pattern space和hold space都可以看作是一个字符串数组
pattern space: sed每读入一行数据, 都存放在这里
hold space: 通过h, H或x操作才会往hold space写入数据
操作patter space和hold space 的相关命令
h: 先清空hold space, 再将pattern space的内容复制到hold space
pattern space +------------+ +------------+
|test string| h |test string|
hold space +------------+ ==> +------------+
| | |test string|
+------------+ +------------+
H: 将pattern space的内容append到hold space, 以'\n'分割pattern space和hold space的内容
pattern space +------------+ +------------+
|string | H |string |
hold space +------------+ ==> +------------+
|test | |test\nstring|
+------------+ +------------+
h可以理解为hold住
g: 先清空pattern space, 再将hold space的内容复制到pattern space
pattern space +------------+ +------------+
|string | g |test |
hold space +------------+ ==> +------------+
|test | |test |
+------------+ +------------+
G: 将hold space的内容append到pattern space, 以'\n'分割pattern space和hold space的内容
pattern space +------------+ +------------+
|string | g |string\ntest|
hold space +------------+ ==> +------------+
|test | |test |
+------------+ +------------+
g可以理解为get
x: 交换hold space和pattern space的内容
pattern space +------------+ +------------+
|string | g |test |
hold space +------------+ ==> +------------+
|test | |string |
+------------+ +------------+
x可以理解为eXchange
了解pattern space和hold space可以做什么
所使用的测试文件:
$ cat testfile
#Linux
Administration
Scripting
Tips and Tricks
#Windows
Administration
#Database
Mysql
Oracle
Queries
Procedures
-
反向输出文件内容, 功能类似tac
$ sed -n ' \#copy first line to hold space 1 h #swap the content of pattern space and hold space except the first line 1 !x #append the content of pattern space to hold space with '\n' 1 !H #copy the content of hold space to pattern space when encounter the last line $ g #print the content of pattern space when encounter the last line $ p ' testfile Procedures Queries Oracle Mysql #Database Administration #Windows Tips and Tricks Scripting Administration #Linux
-
去掉缩进部分的回车
$ sed -n ' #copy the indent line to the hold space /^[ ]\{8\}/ H #when encounter the empty line /^$/ b strip_enter $ b strip_enter b :strip_enter #swap pattern space and hold space x #removed the all '\n' s/\n//g #print the result p ' testfile Administration Scripting Tips and Tricks Administration Mysql Oracle Queries Procedures