echo在第一行追加 echo 追加到文件末尾_linux怎么进入文件的末尾

在本教程中,我们学习在Linux中的文件末尾附加文本的不同方法,Linux中有几种方法可以实现这一点,但是最简单的方法是将命令输出重定向到目标文件,使用> >字符,你可以将命令的结果输出到文本文件。

其他可以实现的方法是使用tee,awk和sed等Linux工具。

将命令或数据的输出重定向到文件结尾

每个基于Unix的操作系统都有一个"输出默认位置"的概念。大家都称它为"标准输出"或"stdout",你的shell (可能bash或zsh )一直在监视缺省输出位置,当你的shell在那里看到有新输出时,它会在屏幕上打印出来,以便你可以看到它。

我们可以使用> >操作符将输出重定向到文件。

过程如下所示:

使用echo命令将文本追加到文件末尾:echo 'sample text line' >> filename.txt

将命令的输出附加到文件末尾:command >> filename.txt

向文件末尾添加行

我们可以使用这个重定向字符使用此方法,如果文件不存在,将创建该文件。

例如:

$ echo"sample line" >> test.txt
$ cat test.txt
sample line
$ echo"sample line 2" >> test.txt
$ cat test.txt
sample line
sample line 2

将命令数据输出结果添加到文件结尾

你还可以添加数据或运行命令并将输出附加到文件。在这个例子中,我们将使用当前日期将添加到文件中,uname命令将打印我们使用的Linux系统的内核版本,

$ date >> test.txt
$ cat test.txt
sample line
sample line 2
Tue Jun 25 20:28:51 UTC 2019
$ uname -r >> test.txt
$ cat test.txt
sample line
sample line 2
Tue Jun 25 20:28:51 UTC 2019
3.13.0-170-generic
$ ls >> test.txt
$ cat test.txt
sample line
sample line 2
Tue Jun 25 20:28:51 UTC 2019
3.13.0-170-generic
test.txt

备选方法

让我们看看如何使用tee,awk和sed Linux工具附加。

使用tee命令行工具

tee命令读取标准输入,并将它写入标准输出和一个或多个文件,它中断程序的输出,使它既可以显示也可以保存在文件中。

$ tee -a test.txt <<
[email protected]:~$ cat test.txt
appended line of text

使用awk命令行工具

Awk是一个实用程序,使程序员可以用语句的形式编写小但有效的程序,Awk主要用于模式扫描和处理。

$ awk 'BEGIN{ printf"another text line appended" >>"test.txt" }'
[email protected]:~$ cat test.txt
another text line appended

使用sed命令行工具

Linux中的sed命令是流编辑器,它可以搜索,查找和替换,插入或删除文件,执行许多功能,

$ sed -i '$a yet another text line' test.txt
[email protected]:~$ cat test.txt
yet another text line

将多行追加到文件

$ echo"line 1" >> result.txt
$ echo"line 2" >> result.txt

下一个变种是在终端输入新行:

echo"line 1
line 2
line 3" >> result.txt

另一种方法是打开文件,并且写入行,直到键入EOT :

$ cat <> result.txt
line 1
line 2
EOT