使用sed在指定内容前后添加字段

要求:在1111之前添加AAA,命令如下:

sed -i 's/指定的字符/要插入的字符&/'  文件

[root@localhost ~]# sed -i  's/1111/AAA&/' /tmp/input.txt                     

[root@localhost ~]# cat /tmp/input.txt                   
null
0000 AAA 11112222

 要求:在1111之后添加BBB,命令如下:

sed -i 's/指定的字符/&要插入的字符/'  文件

[root@localhost ~]# sed -i  's/1111/&BBB/' /tmp/input.txt    

[root@localhost ~]# cat /tmp/input.txt                   
null
0000 AAA 1111 BBB 2222
 
要求:删除所有空行,命令如下
[root@localhost ~]# sed  '/^$/d'  /tmp/input.txt   
null
0000 BBB 1111 AAA 2222
 
要求:一行中,如果包含"1111",则在"1111"前面插入"AAA",在"11111"后面插入"BBB",命令如下:
[root@localhost ~]# sed  's/1111/AAA&/;s/1111/&BBB/'  /tmp/input.txt    
null
0000 BBB 1111 AAA 2222
test
 
要求:在每行的头添加字符,比如"HEAD",命令如下:
[root@localhost ~]# sed -i  's/^/HEAD&/'  /tmp/input.txt 
[root@localhost ~]# cat /tmp/input.txt
HEADnull
HEAD 000011112222
HEAD
HEADtest
 
 要求:在每行的尾部添加字符,比如"tail",命令如下:
[root@localhost ~]# sed -i  's/$/&tail/'  /tmp/input.txt      
[root@localhost ~]# cat /tmp/input.txt                
HEADnulltail
HEAD 000011112222 tail
HEADtail
HEADtesttail

猜你喜欢

转载自www.cnblogs.com/lyongyong/p/12408597.html