1、文件结尾追加

单行插入(简略、间接)

平时最罕用的办法了。

$ echo "test append content" >> test.txt** 文件内容 **$ cat test.txttest append content

这里得留神点如果咱们插入的是零碎变量如:$PATH、$HOME须要应用英文单引号引起来,否则会echo命令会解析成以后零碎变量的的值而后在插入。

让我用示例打动你:

echo "$HOME test append content" >> test.txt** 文件内容 **$ cat test.txttest append content/home/www test append contentecho '$HOME test append content' >> test.txt** 文件内容 **$ cat test.txttest append content/home/www test append content$HOME test append content

多行追加 (简略、十分实用)

利用 "<<EOF EOF"段追加 ↓↓↓

$ cat >> test.txt <<EOF> hello!>   linux> bye!> EOF** 文件内容 **$ cat test.txttest append content/home/www test append content$HOME test append contenthello!  linuxbye!

利用零碎办法"echo "追加 ↓↓↓

** 须要换行的间接回车符即可 ** echo "hello> ceshi> append" >> test.txt** 文件内容 **$ cat test.txttest append content/home/www test append content$HOME test append contenthello!  linuxbye!helloceshiappend

两头小彩蛋,文件内容有点多了,把内容革除了

$ > test.txt$ cat test.txt** 文件内容 空洞无物**

上述echo办法也能够应用-e来申明本义信息

$ echo -e "hello\nworld" >> test.txt** 文件内容 **$ cat test.txthelloworld

应用零碎主动中断

** 利用 CRT+c OR CRT+d 中断写入即可 **$ cat >> test.txttestappendcontent^C ** 文件内容 **$ cat test.txthelloworldtestappendcontent

2、指定的行前/后插入指定内容

这个就得应用Linux中传说的三剑客之一了【sed】
sed这个东东解决文件内容十分弱小,而且用多了会上瘾,得谨慎。

以下做简略演示

** 以后文件内容 **$ cat test.txthelloworldtestappendcontent

指定关键词后最贱

在”test"关键词后插入插入"sed match insert"

** 留神:    a:append,即在'test'后追加 [sed -i '/test/a\sed match insert' test.txt]    i:insert,即在'test'前追加 [sed -i '/test/i\sed match insert' test.txt]**$ sed -i '/test/a\sed match insert' test.txt ** 文件内容 **$ cat test.txthelloworldtestsed match insertappendcontent

指定行号下追加

** 2a\2i这里的a、i同上 **$ sed -i '2a\ceshi line' test.txt** 文件内容 **$ cat test.txthelloworldceshi linetestsed match insertappendcontent

参考文档:https://blog.51cto.com/laokeb...