文件编辑:将不存在的行追加到文件

linuxoperating systemopen source更新于 2026/1/29 19:37:17

有时需要将一行或字符串追加到文件,以便在不删除现有数据的情况下更改输出。在文件现有行之间添加多行是修改文件的有效方法。

"追加"表示将数据添加到文件而不删除当前可用数据。要将行追加到文件中,可以使用各种命令,例如 printf、echo、tee、cat 等。

虽然追加行很容易,但许多初学者总是需要澄清。因此,本教程将介绍将不存在的行追加到文件的简单方法。

文件编辑:将不存在的行追加到文件

">>"运算符可以重定向文件的输出。如果指定的文件不存在,它会自动创建该文件,然后添加行。使用此运算符,您可以使用多个命令向文件添加新行。

您将借助命令打印行,而">>"运算符将在文件中打印此行。例如,我们有一个名为"Linux.txt"的文件,其中包含以下信息:

:~$ cat Linux.txt
  What does append mean in Linux?

在此文件中,我们将借助几个不同的命令添加新行。

printf 命令

"printf"命令允许您写入、格式化参数,并将参数转换为标准输出。首先,我们将了解如何使用">>"向文件添加新行。运算符与 printf 命令一起使用 -

:~$ printf "<Text_line> 
" >> <file_name>

现在,让我们使用以下命令在"Linux.txt"文件中添加一个新行 -

:~$ printf "You can append a line through various commands in the terminal. 
" >> Linux.txt :~$ cat Linux.txt What does append mean in Linux? You can append a line through various commands in the terminal.

您可以看到,运行上述命令会在文件中添加一个新行。

Echo 命令

使用内置命令"echo",您可以通过将字符串/文本行作为参数传递,在 Linux 中显示该字符串/文本行。

:~$ echo "<new_text>" >> <file_name>

让我们尝试在 Linux.txt 中再次添加该行 -

:~$ echo "You can append a line through various commands in the terminal. 
" >> Linux.txt :~$ cat Linux.txt What does append mean in Linux? You can append a line through various commands in the terminal.

Tee 命令

Linux 中的 tee 命令读取输入并将其打印到一个或多个文件中。通过此命令,您可以将一个文件的输入打印到另一个文件中。此外,您还可以使用 tee 命令直接在文件中打印新行。

:~$ cat <source file_name> | tee -a <target file_name>

例如,我们将使用此命令将 Info.txt 文件的内容打印到 Linux.txt 文件中。首先,我们用 cat 命令将 Info.txt 文件中的行作为输入。然后,我们将通过管道传输 tee 命令,将此输入打印到 Linux.txt 文件中。

:~$ cat Info.txt | tee -a Linux.txt
You can append a line through various commands in the terminal.
:~$ cat Linux.txt 
What does append mean in Linux? 

You can append a line through various commands in the terminal.

除此之外,您还可以使用 echo 命令直接向文件添加新行。同样的方法也可以使用 echo 命令打印该行,然后使用 tee 命令将其通过管道传输。

:~$ echo "<text_line>" | tee -a <file_name>

在上述命令中,-a 选项会将给定文件的一行内容添加到文件中。让我们将这组命令组合应用到文件中 -

:~$ echo "You can append a line through various commands in the terminal." | tee -a Linux.txt
You can append a line through various commands in the terminal.
:~$ cat Linux.txt
What does append mean in Linux? 

You can append a line through various commands in the terminal.

Cat 命令

强大而通用的 cat 命令主要用于显示文件内容。此外,您还可以将一个文件的内容打印到另一个文件 -

:~$ cat <source file_name> >> <target file_name>

在这里,我们将再次使用 cat 命令将"Linux1.txt"文件的内容附加到"Linux.txt"文件中。

:~$ cat Info.txt >> Linux.txt
:~$ cat Linux.txt
What does append mean in Linux? 

Append means simply add the data to the file erasing existing data.

结论

本文介绍了将不存在的行追加到文件的简单方法。我们解释了四种在不修改现有输出的情况下追加行的方法。请确保正确使用所有命令,因为不合适的命令有时会导致错误。此外,您还可以访问我们的官方网站了解更多关于 Linux 的信息。


相关文章


有用资源