1.概述
在前面的章节中,我们已经介绍了shell结构化命令,函数用法,正则表达式以及sed,gawk的基本用法,在这里,主要介绍一下sed和awk的高级用法。sed是流编辑器,具有速度快的优点。sed 每次处理一行数据,在每一行数据上执行脚本命令。而gawk是一种编程语言,能够对数据进行处理,从而生成数据报告。
2. sed的高级用法
(1)n与N的区别
n: 小写n告诉sed编辑器移动到数据流中文本的下一行,而不是回到命令的开始。
N: 大写N是将数据流的下一行添加到模式空间中去。即将数据流的两个文本行合并,添加到同一模式空间中去。虽然文本行以换行符分隔,但此时流sed编辑器已经将他们作为同一个文本进行处理了。
例子:
[root@localhost chapter18]# cat <data1
this is the header line
this is a data line.
this is the last line.
data1中的数据隔一行有一个空行。
小写n:
[root@localhost chapter18]# sed '/header/{
n
d
}' data1
this is the header line
this is a data line.
this is the last line.
{}表示在匹配header上执行下面的脚本。
即匹配了data1中的第一行,然后n,移动到下一行,d删除下一行文本,此时就删除了空行。
大写N:
[root@localhost chapter18]# sed '/header/{
N
d
}' data1
this is a data line.
this is the last line.
匹配了data1中的第一行,N将下一行添加到模式空间中去,那么此时流编辑器就把它们作为一行处理了,虽然它们之间有换行符,所以d就删除了两行,分别是第一行与空行。
有{}与无{}的区别:
[root@localhost chapter18]# sed '/header/n;d;' data1
this is the header line
这个命令与上面的命令形式是一样的,只不过用;将命令分隔开了。
首先匹配header,然后下一行,之后一直删除下一行。所以只留下了第一行。
[root@localhost chapter18]# sed '/header/N;d;' data1
如果是N就全删除了。
首先匹配header,然后把下一行添加到模式空间中去,d删除掉模式空间的内容。之后扫描下一行,N把next添加到模式空间中去......
(2) D与d的区别
d是删除模式空间的当前行。
而D只删除模式空间的第一行,直至换行符的所有字符,也包括换行符。
d Delete pattern space. Start next cycle.、
D Delete up to the first embedded newline in the pattern space. Start next cycle, but skip reading from the input if there is still data in the pattern space.
区别一下:
d 删除模式空间,进行下一个循环,即处理下一行。
D删除模式空间的第一行,如果此时模式空间仍然有数据,强制返回到脚本的开头,则不处理新的输入的数据。
例子1:
[root@localhost chapter18]# cat <data5
This is the header line.
this is the second line.
this is the last line.
[root@localhost chapter18]# sed '/^$/{
> N
> /heade/D}' data5
This is the header line.
this is the second line.
this is the last line.
例子2:
[root@localhost chapter18]# sed '/^$/N;/header/D' data5
this is the second line.
this is the last line.
这是个比较经典的例子。
分析:
目标: 删除第一行之前的空行。
例子1:
首先通过^$找到空行,然后N将下一行添加到模式空间中去,/header/D 匹配模式空间的内容,所以D就删除了第一个行,直到换行符为止。
而此时模式空间还有内容,但由于不是空行,与/^$/不匹配所以就不会执行下面的脚本。
所以最终只删除了模式空间的第一行。
例子2:
前面的过程是一样的,通过D删除了第一个行,直到换行符为止。但由于模式空间中还有内容,必须处理, 与^$不匹配,不执行N,但与/header/D匹配,所以就删除了第二行。所以header那一行也被删除了。
主要是{}里面的命令都会执行到前面的模式匹配上。
对于D,d,n,N,{},一定要注意区分。
(3)保留空间与模式空间
模式空间是一个活动缓冲,它在sed编辑器处理命令时保留被检查