Linux终端文件追加操作
文章目录
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
content2、指定的行前/后插入指定内容
这个就得使用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
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论