sed 想删除文件中的指定行,是可以用行号指定也可以用RE来匹配的。


删除指定的行【可以指定行号删除、匹配字符串来删除】

[root@Jason64-17 ~]# cat -n seq.txt
     1   ok i will help you
     2   understand sed usage
     3   how to use it
     4   and we should use it in view
     5   now let us
     6   go
     7   hello  my name is
[root@Jason64-17 ~]# cat -n seq.txt | sed 3d
     1   ok i will help you
     2   understand sed usage
     4   and we should use it in view
     5   now let us
     6   go
     7   hello  my name is
[root@Jason64-17 ~]# cat -n seq.txt | sed /should/d
     1   ok i will help you
     2   understand sed usage
     3   how to use it
     5   now let us
     6   go
     7   hello  my name is
[root@Jason64-17 ~]# cat -n seq.txt | sed /ow/d
     1   ok i will help you
     2   understand sed usage
     4   and we should use it in view
     6   go
     7   hello  my name is
[root@Jason64-17 ~]# cat -n seq.txt | sed -r /how\|should/d 
     1   ok i will help you
     2   understand sed usage
     5   now let us
     6   go
     7   hello  my name is


删除最后几行


[root@Jason64-17 ~]# seq 5 > seq01.txt                                      
[root@Jason64-17 ~]# cat seq01.txt
1
2
3
4
5
[root@Jason64-17 ~]# for((i=1;i<4;i++)); do sed -i '$d' seq01.txt ; done  
#C式for循环 
[root@Jason64-17 ~]# cat seq01.txt
1
2
[root@Jason64-17 ~]# seq 5 > seq01.txt
[root@Jason64-17 ~]# cat seq01.txt    
1
2
3
4
5
[root@Jason64-17 ~]# i=1; while [ $i -le 3 ]; do sed -i '$d' seq01.txt; ((i++)); done
#while循环  
[root@Jason64-17 ~]# cat seq01.txt
1
2
[root@Jason64-17 ~]# seq 5 > seq01.txt
[root@Jason64-17 ~]# cat seq01.txt
1
2
3
4
5
[root@Jason64-17 ~]# for i in `seq 3`; do sed -i '$d' seq01.txt ; done
#bash for循环
[root@Jason64-17 ~]# cat seq01.txt    
1
2
[root@Jason64-17 ~]# seq 5 > seq01.txt
[root@Jason64-17 ~]# cat seq01.txt    
1
2
3
4
5
#until 循环
[root@Jason64-17 ~]# seq 5 > seq01.txt
[root@Jason64-17 ~]# cat seq01.txt    
1
2
3
4
5
[root@Jason64-17 ~]# i=3; until [ $i -le 0 ]; do sed -i '$d' seq01.txt ; ((i--)); done
[root@Jason64-17 ~]# cat seq01.txt
1
2
[root@Jason64-17 ~]#


上述例子都是删除了最后3行的要求。