Linux sed命令在匹配行前后插入新行

有时候经常需要在匹配行的前后插入新行,之前各种找资料,现在记录一下。

参数说明

使用sed命令配合以下参数即可实现,

a\ 在匹配行的后面追加一行 
b\ 在匹配行的前面追加一行

sed的man手册说明如下,

a \
text   Append text, which has each embedded newline preceded by a backslash.
i \
text   Insert text, which has each embedded newline preceded by a backslash.

具体使用

假定有以下脚本,

#!/bin/bash

cat a >> b

需要在cat之前先判断该文件是否存在,因此需要添加一个if判断,可如下操作,

[root@CentOS-7-2 /home]# cat test.sh 
#!/bin/bash

cat a >> b
[root@CentOS-7-2 /home]# sed -i "/cat/i\if [ -f a ];then" test.sh 
[root@CentOS-7-2 /home]# sed -i "/cat/a\fi" test.sh 
[root@CentOS-7-2 /home]# cat test.sh 
#!/bin/bash

if [ -f a ];then
cat a >> b
fi
[root@CentOS-7-2 /home]# 

以cat为关键字匹配行,然后在该行之前添加if判断,在该行之后添加fi,结束if语句。

不过此时好像格式不太好看,那就再补一刀,在匹配字符前插入字符。

[root@CentOS-7-2 /home]# cat test.sh 
#!/bin/bash

if [ -f a ];then
cat a >> b
fi
[root@CentOS-7-2 /home]# sed -i "s/cat/    &/" test.sh 
[root@CentOS-7-2 /home]# cat test.sh 
#!/bin/bash

if [ -f a ];then
    cat a >> b
fi
[root@CentOS-7-2 /home]# 

相应的,在匹配字符后插入字符可如下操作,

[root@CentOS-7-2 /home]# cat test.sh 
#!/bin/bash

if [ -f a ];then
    cat a >> b
fi
[root@CentOS-7-2 /home]# sed -i "s/>> b/&;echo ok/" test.sh 
[root@CentOS-7-2 /home]# cat test.sh 
#!/bin/bash

if [ -f a ];then
    cat a >> b;echo ok
fi
[root@CentOS-7-2 /home]# 

如果想在匹配行的行首或者行尾插入字符,只要将关键字替换为行首行尾的标识符:^和$

猜你喜欢

转载自blog.csdn.net/u010039418/article/details/81082570