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
0000AAA11112222
 
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
0000AAA1111BBB2222
 
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
0000BBB1111AAA2222
test

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

1
2
3
4
5
6
[root@localhost ~]# sed -i 's/^/HEAD&/' /tmp/input.txt 
[root@localhost ~]# cat /tmp/input.txt
HEADnull
HEAD000011112222
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
HEAD000011112222tail
HEADtail
HEADtesttail

說明:
1."^"代表行首,"$"代表行尾
2.'s/$/&tail/g'中的字符g代表每行出現的字符全部替換,如果想在特定字符處添加,g就有用了,否則只會替換每行第一個,而不繼續往後找。

本文出自https://www.cnblogs.com/Dev0ps/p/8441255.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章