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