您的位置:首页 > 运维架构 > Shell

SHELL 在指定行的前/后插入指定内容

2017-04-01 13:59 148 查看
原文件:

[root@xiaowu shell]# cat -n file 

     1  aaaa

     2  bbbb

     3  cccc

     4  dddd

现在要在第二行即“bbbb”行的下面添加一行,内容为“xiaowu”

[root@xiaowu shell]# sed '/bbbb/a\xiaowu' file 
aaaa
bbbb
xiaowu
cccc
dddd

如果要加两行“xiaowu”可以用一下语句,注意用“\n”换行

[root@xiaowu shell]# sed '/bbbb/a\xiaowu\nxiaowu' file 
aaaa
bbbb
xiaowu
xiaowu
cccc
dddd

如果要在第二行即“bbbb”行的上添加一行,内容为“xiaowu”,可以把参数“a”换成“i”

[root@xiaowu shell]# sed '/b/i\xiaowu' file 
aaaa
xiaowu
bbbb
cccc
dddd

以上文件中只有一行匹配,如果文件中有两行或者多行匹配,结果有是如何呢?

[root@xiaowu shell]# cat -n file 
     1  aaaa
     2  bbbb
     3  cccc
     4  bbbb
     5  dddd

[root@xiaowu shell]# sed '/bbbb/a\xiaowu' file 
aaaa
bbbb
xiaowu
cccc
bbbb
xiaowu
dddd

由结果可知,每个匹配行的下一行都会被添加“xiaowu”

那么如果指向在第二个“bbbb”的下一行添加内容“xiaowu”,该如何操作呢?

可以考虑先获取第二个“bbbb”行的行号,然后根据行号在此行的下一行添加“xiaowu”

获取第二个“bbbb”行的行号的方法:

方法一:

[root@xiaowu shell]# cat -n file |grep b |awk '{print $1}'|sed -n "2"p
4

方法二:

[root@xiaowu shell]# sed -n '/bbbb/=' file |sed -n "2"p
4

由结果可知第二个“bbbb”行的行号为4,然后再在第四行的前或后添加相应的内容:

[root@xiaowu shell]# sed -e '4a\xiaowu' file 
aaaa
bbbb
cccc
bbbb
xiaowu
dddd
[root@xiaowu shell]# sed -e '4a\xiaowu\nxiaowu' file 
aaaa
bbbb
cccc
bbbb
xiaowu
xiaowu
dddd

向指定行的末尾添加指定内容,比如在“ccccc”行的行尾介绍“ eeeee”

[root@xiaowu shell]# cat file
aaaaa
bbbbb
ccccc
ddddd
[root@xiaowu shell]# sed 's/cc.*/& eeeee/g' file
aaaaa
bbbbb
ccccc eeeee
ddddd
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: