使用sed在指定内容前后添加字段、删除过滤字段、替换过滤字段

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

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

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

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

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

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

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

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

 要求:替换查找过滤字段

[root@localhost ~]# sed -i s/HEAD000011112222tail/11111/ /tmp/input.txt

[root@localhost ~]# cat /tmp/input.txt                
11111
HEADtail
HEADtesttai

备注:如果替换字符中带有/符号,

正常操作会报错如下:

sed: -e expression #1, char 13: unknown option to `s'

报错是因为替换的字符串包含有分隔符/

所以这行改一下分隔符就可以解决问题了

改成感叹号!或者|  等其他来分割

说明:
1."^"代表行首,"$"代表行尾
2.'s/$/&tail/g'中的

  字符s,表示查找替换;

  字符&,表示引用前面引用的字段;

  字符g代表每行出现的字符全部替换(也叫行内全局替换),如果想在特定字符处添加,g就有用了,否则只会替换每行第一个,而不继续往后找。

3. 在命令中 /// 和 @@@ 和### 符号等价;

如 sed -i ‘s/1/2/g’ == sed -i 's@1@2@g' == sed -i 's#1#2#g'

原文地址:https://www.cnblogs.com/lyongyong/p/12408597.html