#如果知道行号可以用下面的方法 sed -i '88 r b.file' a. file #在a.txt的第88行插入文件b.txt awk '1;NR==88{system("cat b.file")}' a. file > a. file #如果不知道行号,可以用正則匹配 sed -i '/regex/ r b.txt' a.txt # regex是正则表达式 awk '/target/{system("cat b.file")}' a. file > c. file #sed的話如果不改变源文件,可以去掉-i开关,修改会输出到STDOUT 原文件: [root@xiaowu shell]# cat -n file 现在要在第二行即“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 [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 |
|
来自: joy_chen > 《sed or awk》