Contents

将行追加到文件

1.概述

在本教程中,我们将学习如何在 Linux 中将行追加到文件的末尾。 将行附加到文件末尾有两种标准方法:“ »”重定向运算符和tee 命令。两者可以互换使用,但tee的语法更冗长,并允许扩展操作。

2. 追加一行

我们可以使用输出重定向运算符“»”将一行文本附加到文件中:

$ echo "I am blogdemo" >> destination.txt

同样可以使用tee来完成:

$ echo "I am blogdemo with tee command" | tee -a destination.txt

3. 追加多行

为了追加多行,我们可以使用echo 命令,然后按回车键输入多行。完成后,我们只需使用重定向附加运算符“»”:

$ echo "I just wrote a great tutorial for blogdemo
> and I believe it will increase your understanding 
> of the Linux operating system" >> destination.txt

完成此操作的另一种方法是使用cat 命令并包含一个表示文件结尾 (EOF) 的字符串:

$ cat << EOF >> destination.txt 
> I just added some more good stuff
> tell me what you think 
> EOF

同样可以使用tee命令完成:

$ cat << EOF | tee -a destination.txt
> I just added some more good stuff
> tell me what you think
> EOF

4. 附加stdoutstderr

默认情况下,重定向运算符仅附加stdout流。为了让我们能够附加stderr,我们需要指定它。 为了追加到同一个文件,我们可以在“»”之前放置“&”符号:

$ cat not_there.txt &>> output_and_error.txt

如果我们想将这些流拆分成不同的文件,我们可以通过指定哪些流去哪里来完成它:

$ cat not_there.txt >> destination.txt 2>> output_and_error.txt

5. 附加sudo

sudo 命令可以方便地在系统根级别运行命令。为了将它与我们一直在探索的重定向机制结合起来,我们需要调用bash作为命令并将我们想要运行的命令作为参数传递:

$ sudo bash -c 'echo "I just added some text using Sudo" >> destination.txt'

至于tee命令,我们直接用sudo调用即可:

$ echo "I just did this using Sudo again" | sudo tee -a destination.txt