[20230610]sed实现特定行追加文件内容.txt
--//业务需要,要实现特定行追加文件内容,看了一些文档,做一个记录。
$ cat a1.txt
1111111
PPPPPPP
4444444
$ cat a2.txt
222222
333333
--//要求输出如下:
1111111
222222
333333
4444444
1.使用vim:
cd d:\tools\cygwin64\home\Administrator\other
D:\tools\Vim\vim80\vim -c "/^PPPPPP" -c ":d" -c ":-1" -c ":r a2.txt" -c ":wq! a3.txt" a1.txt
$ cat a3.txt
1111111
222222
333333
4444444
2.使用sed 方法1:
$ sed -e "/^PPPPPP/r a2.txt" -e "/^PPPPP/d" a1.txt
1111111
222222
333333
4444444
3.使用sed 方法2:
$ a=$(grep -n "^PPPPPP" a1.txt | head -1 | cut -f1 -d:)
$ echo $a
2
--//如果行号是bash shell变量,有点麻烦。
$ echo "sed -n -e '1,$((a-1))p' a1.txt" | bash
1111111
$ echo "sed -n -e '$((a+1)),\$p' a1.txt" | bash
4444444
--//也可以写成如下:
$ sed -n -e '1,'$((a-1))' p' a1.txt
1111111
$ sed -n -e ''$((a+1))',$ p' a1.txt
4444444
--//感觉代码不好看。
--//还是第二种方法看起来更加实在一些。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/267265/viewspace-2959719/ ,如需转载,请注明出处,否则将追究法律责任。