sed匹配行前行后加入一行数据
a 追加内容 sed '/匹配内容/a\要加入的内容' test.file(将内容追加到匹配内容目标行的下一行位置)
i 插入内容 sed '/匹配内容/i\要加入的内容' test.file (将内容插入到匹配内容目标行的上一行位置)
Example:
#我需要把文件中包含'10.0.1.110'这个关键词的行前或行后加入内容为"10.0.1.119 sendhost"一行记录
test.file 文件内容如下:
[root@mhost contorl]# cat test.file
10.0.1.114 masterweb
10.0.1.112 coredb1
10.0.1.110 wwwweb
10.0.1.113 coredb2
10.0.1.111 cache1
10.0.1.110 cache2
10.0.1.115 cache3
加在行后
[root@mhost contorl]# sed '/10.0.1.110/a\10.0.1.119 sendhost' test.file 10.0.1.114 masterweb 10.0.1.112 coredb1 10.0.1.110 wwwweb 10.0.1.119 sendhost 已经加上 10.0.1.113 coredb2 10.0.1.111 cache1 10.0.1.110 cache2 10.0.1.119 sendhost 已经加上 10.0.1.115 cache3 #如果要精确匹配就是要把内容加到10.0.1.110 cache2下面一行的话,匹配内容就要精确 [root@mhost contorl]# sed '/10.0.1.110 cache2/a\10.0.1.119 sendhost' test.file 10.0.1.114 masterweb 10.0.1.112 coredb1 10.0.1.110 wwwweb 10.0.1.113 coredb2 10.0.1.111 cache1 10.0.1.110 cache2 10.0.1.119 sendhost 已经加上 10.0.1.115 cache3
加在行前
[root@mhost contorl]# sed '/10.0.1.110/i\10.0.1.119 sendhost' test.file 10.0.1.114 masterweb 10.0.1.112 coredb1 10.0.1.119 sendhost 已经加上 10.0.1.110 wwwweb 10.0.1.113 coredb2 10.0.1.111 cache1 10.0.1.119 sendhost 已经加上 10.0.1.110 cache2 10.0.1.115 cache3 #如果要精确匹配就是要把内容加到10.0.1.110 cache2上面一行的话,匹配内容就要精确 [root@mhost contorl]# sed '/10.0.1.110 cache2/i\10.0.1.119 sendhost' test.file 10.0.1.114 masterweb 10.0.1.112 coredb1 10.0.1.110 wwwweb 10.0.1.113 coredb2 10.0.1.111 cache1 10.0.1.119 sendhost 已经加上 10.0.1.110 cache2 10.0.1.115 cache3**确认修改没有问题sed -i 加-i 尝试然后放心修改!