关于linux:Linux终端文件追加操作

7次阅读

共计 1561 个字符,预计需要花费 4 分钟才能阅读完成。

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…

正文完
 0