一、使用地址
默认情况下,在sed编辑器中使用的命令应用于所有文本行,如果仅想将命令应用于某一特定的文本或一组文本行,则必须使用行寻址。
在sed编辑器中,有两种寻址形式:
(1)行的数值范围
(2)筛选的文本模式。
在命令中指定的地址的格式如下:
[address] command
也可以将多个命令应用于一个地址 address{
command1
command2
command3
}
1.数字寻址可以用数字指定某一行或一个行区间
通过数字指定只处理指定行
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '2s/i have/he has/' test.txt
i have an apple
he has a pen
i have a pear
通过数字指定只处理指定区间的行
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '1,2s/i have/he has/' test.txt
he has an apple
he has a pen
i have a pear
可以用'$'表示最后一行。$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '1,$s/i have/he has/' test.txt
he has an apple
he has a pen
he has a pear
二、使用模式过滤器当文本行能够匹配指定模式时才处理。
命令格式:
/pattern/command
sed编辑器支持pattern为正则表达式。例如如果想为用户名为jie的用户更改默认的shell,可以使用sed命令:$ sed '/jie/s/bash/sh' /etc/passwd
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '/an/s/i/you/' test.txt
you have an apple
i have a pen
i have a pear
三、使用组合命令$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '1,3{s/i/you/
s/apple/orange/}' test.txt
you have an orange
you have a pen
you have a pear
至此,sed命令的替换命令基本学习完毕,接下来学习其它sed命令。