linux中sed在指定字符前后添加内容

假设文档内容如下:
1
2
3
4
5
[root@localhost ~]# cat /tmp/input.txt
null
000011112222
 
test

要求:在1111之前添加AAA,方法如下:

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

1
2
3
4
5
6
[root@localhost ~]# sed -i   's/1111/AAA&/'  /tmp/input.txt                     
[root@localhost ~]# cat /tmp/input.txt                   
null
0000 AAA 11112222
 
test

 要求:在1111之后添加BBB,方法如下:

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

1
2
3
4
5
6
[root@localhost ~]# sed -i   's/1111/&BBB/'  /tmp/input.txt    
[root@localhost ~]# cat /tmp/input.txt                   
null
0000 AAA 1111 BBB 2222
 
test

要求:(1) 删除所有空行;(2) 一行中,如果包含"1111",则在"1111"前面插入"AAA",在"11111"后面插入"BBB"

1
2
3
4
[root@localhost ~]# sed  '/^$/d;s/1111/AAA&/;s/1111/&BBB/'  /tmp/input.txt   
null
0000 BBB 1111 AAA 2222
test

 要求:在每行的头添加字符,比如"HEAD",命令如下:

1
2
3
4
5
6
[root@localhost ~]# sed -i  's/^/HEAD&/'  /tmp/input.txt 
[root@localhost ~]# cat /tmp/input.txt
HEADnull
HEAD 000011112222
HEAD
HEADtest

  要求:在每行的尾部添加字符,比如"tail",命令如下:

 

1
2
3
4
5
6
[root@localhost ~]# sed -i  's/$/&tail/'  /tmp/input.txt      
[root@localhost ~]# cat /tmp/input.txt                
HEADnulltail
HEAD 000011112222 tail
HEADtail
HEADtesttail

说明:
1."^"代表行首,"$"代表行尾


2.'s/$/&tail/g'中的字符g代表每行出现的字符全部替换,如果想在特定字符处添加,g就有用了,否则只会替换每行第一个,而不继续往后找。

转载于:https://www.cnblogs.com/quliuliu2013/p/8490353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值