替换命令并不是sed编辑器可用的唯一命令,如果有其它需要,sed编辑器还提供了删除命令、插入命令、附加命令、修改命令、变换命令。
一、删除命令
这两个命令很容易搞混,放在一起学习。
插入命令i:在指定行之前添加新的一行。
附加命令a: 在指定行之后添加新的一行。
命令格式如下:
命令选项为c,修改匹配指定模式的文本行,使用方法与插入命令相同。
变换命令是唯一对单个字符进行操作的sed编辑器命令,格式如下:
[address]y/inchars/outchars/
变换命令将inchars和outchars中的字符一一映射,将inchars的第i个字符转换为outchars在的第i个字符,如果inchars和outchars长度不同,sed编辑器会报错。
一、删除命令
删除命令d将删除与所给定模式匹配的文本行,使用这个命令时要小心,默认情况下会处理所有文本行,通常与地址一起使用。
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed 'd' test.txt
$ sed '/an/d' test.txt
i have a pen
i have a pear
$ sed '1,2d' test.txt
i have a pear
注意:这里的d放在了最后,跟替换命令中的s放的位置不同。sed编辑器不会改变原文件,仅仅是将处理结果放到stdout中去。也可以使用两个文本模式删除行,sed命令将首先找到匹配第一个模式的文本行(如果有多行匹配,以第一行为准),然后打开删除功能,找到匹配第二个模式的文本行(如果有多行匹配,以第一行为准),然后删除命令会处理这两行之间的所有文本行。最后关闭删除功能。如果下面还有模式可以匹配第一个模式,又打开删除功能,类似这样一直到所有文本行处理完毕。
$ cat test.txt
i have an apple
i have an apple
i have a pen
i have a pear
this is 4th line
this is 4th line
this is 5th line
this is 6th line
$ sed '/an/,/4th/d' test.txt
this is 4th line
this is 5th line
this is 6th line
下面这个命令展示了多模式删除有时候会得到意想不到的结果。
$ cat test.txt
i have an apple
i have an apple
i have a pen
i have a pear
this is 4th line
this is 4th line
this is 5th line
this is 6th line
i have an apple
i have a pen
i have a pear
i say this is 14th line
$ sed '/an/,/4th/d' test.txt
this is 4th line
this is 5th line
this is 6th line
如果第二个匹配模式无法找到,则会将最后一行当作第二个匹配行。
$ sed '/pen/,/4thxx/d' test.txt
i have an apple
i have an apple
二、插入与附加命令
这两个命令很容易搞混,放在一起学习。
插入命令i:在指定行之前添加新的一行。
附加命令a: 在指定行之后添加新的一行。
命令格式如下:
sed '[address]command \
new line'
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '2i \
this is a insert line before line 2' test.txt
i have an apple
this is a insert line before line 2
i have a pen
i have a pear
$ sed '2a \
this is a append line after line 2' test.txt
i have an apple
i have a pen
this is a append line after line 2
i have a pear
在最后一行插入附加可以用'$'表示最后一行。
$ sed '$a \
this is a append line after the last line' test.txt
i have an apple
i have a pen
i have a pear
this is a append line after the last line
如果要添加的文本行有多行,在每一个新文本行之前使用'\'。
$ sed '$a \
this is a append line after the last line \
> this is other append line after the last lien' test.txt
i have an apple
i have a pen
i have a pear
this is a append line after the last line
this is other append line after the last lien
三、修改命令
命令选项为c,修改匹配指定模式的文本行,使用方法与插入命令相同。
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '2c \
this line is modified' test.txt
i have an apple
this line is modified
i have a pear
四、变换命令
变换命令是唯一对单个字符进行操作的sed编辑器命令,格式如下:
[address]y/inchars/outchars/
变换命令将inchars和outchars中的字符一一映射,将inchars的第i个字符转换为outchars在的第i个字符,如果inchars和outchars长度不同,sed编辑器会报错。
$ cat test.t
cat: test.t: No such file or directory
$ cat test.txt
i have an apple
i have a pen
i have a pear
$ sed '1,$y/ia/IA/' test.txt
I hAve An Apple
I hAve A pen
I hAve A peAr