Linux终端文件追加操作
Albert -1、文件结尾追加单行插入(简单、直接)平时最常用的方法了。
$ echo "test append content" >> test.txt
** 文件内容 **
$ cat test.txt
test append content
这里得注意点如果我们插入的是系统变量如:$PATH、$HOME需要使用英文单引号引起来,否则会echo命令会解析成当前系统变量的的值然后在插入。
让我用示例感动你:
echo "$HOME test append content" >> test.txt
** 文件内容 **
$ cat test.txt
test append content
/home/www test append content
echo '$HOME test append content' >> test.txt
** 文件内容 **
$ cat test.txt
test append content
/home/www test append content
$HOME test append content
多行追加 (简单、非常实用)利用 "<<EOF EOF"段追加 ↓↓↓$ cat >> test.txt <<EOF
> hello!
> linux
> bye!
> EOF
** 文件内容 **
$ cat test.txt
test append content
/home/www test append content
$HOME test append content
hello!
linux
bye!
利用系统方法"echo "追加 ↓↓↓** 需要换行的直接回车符即可 **
echo "hello
> ceshi
> append" >> test.txt
** 文件内容 **
$ cat test.txt
test append content
/home/www test append content
$HOME test append content
hello!
linux
bye!
hello
ceshi
append
中间小彩蛋,文件内容有点多了,把内容清除了
$ > test.txt
$ cat test.txt
** 文件内容 空空如也**
上述echo方法也可以使用-e来声明转义信息
$ echo -e "hello\nworld" >> test.txt
** 文件内容 **
$ cat test.txt
hello
world
使用系统自动中断** 利用 CRT+c OR CRT+d 中断写入即可 **
$ cat >> test.txt
test
append
content
^C
** 文件内容 **
$ cat test.txt
hello
world
test
append
content
2、指定的行前/后插入指定内容这个就得使用Linux中传说的三剑客之一了【sed】
sed这个东东处理文件内容非常强大,而且用多了会上瘾?,得慎重。
以下做简单演示
** 当前文件内容 **
$ cat test.txt
hello
world
test
append
content
指定关键词后最贱在”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.txt
hello
world
test
sed match insert
append
content
指定行号下追加** 2a\2i这里的a、i同上 **
$ sed -i '2a\ceshi line' test.txt
** 文件内容 **
$ cat test.txt
hello
world
ceshi line
test
sed match insert
append
content
参考文档:https://blog.51cto.com/laokeb...
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。