10.3.2 删除
使用d命令可删除指定的行,示例如下:
#
将file
的第一行删除后输出到屏幕
#
你应该知道如何删除第二行了
[root@localhost ~]# sed '1d' Sed.txt
this is line 2, the Second line, Empty line followed
this is line 4, this is Third line
this is line 5, this is Fifth line
#
由于sed
默认不修改原文件,如果希望保存修改后的文件则需要用重定向
sed '1d' Sed.txt > saved_file
#
如果想直接修改文件,使用-i
参数
#
这里不会有任何输出,而是直接修改了源文件,删除了第一行
Sed -i '1d' file
#
删除指定范围的行(第1
行到第5
行)
[root@localhost ~]# sed '1,3d' Sed.txt
this is line 4, this is Third line
this is line 5, this is Fifth line
#
删除指定范围的行(第一行到最后行)
[root@localhost ~]# sed '1,$d' Sed.txt
[root@localhost ~]# #
清空了Sed.txt
文件
#
删除最后一行
[root@localhost ~]# sed '$d' Sed.txt
this is line 1, this is First line
this is line 2, the Second line, Empty line followed
this is line 4, this is Third line
#
删除除指定范围以外的行(只保留第5
行)
#
要删除其他的行请举一反三
[root@localhost ~]# sed '5!d' Sed.txt
this is line 5, this is Fifth line
#
删除所有包含Empty
的行
[root@localhost ~]# sed 'Emptyd' Sed.txt
this is line 1, this is First line
this is line 4, this is Third line
this is line 5, this is Fifth line
#
删除空行
[root@localhost ~]# sed '^$d' Sed.txt
this is line 1, this is First line
this is line 2, the Second line, Empty line followed
this is line 4, this is Third line
this is line 5, this is Fifth line