如何将命令的输出附加到文本文件的末尾?


当前回答

使用tee和选项-a(——append)允许您一次追加到多个文件,也可以使用sudo(在追加到受保护的文件时非常有用)。除此之外,如果您需要使用bash之外的其他shell,这很有趣,因为并非所有shell都支持>和>>操作符

echo "hello world" | sudo tee -a output.txt

这个帖子有关于tee的很好的答案

其他回答

我经常把两者混淆。最好通过它们的输出来记住:

>表示覆盖

$ touch someFile.txt
$ echo ">" > someFile.txt
$ cat someFile.txt
  >
$ echo ">" > someFile.txt
$ cat someFile.txt
  >

>>表示追加

$ echo ">" > someFile.txt
$ cat someFile.txt
  >
$ echo ">" >> someFile.txt
$ cat someFile.txt
  >>

您可以使用>>操作符。这将把命令中的数据附加到文本文件的末尾。

要测试这个,请运行:

echo "Hi this is a test" >> textfile.txt

这样做几次,然后运行:

cat textfile.txt

您将看到文本被多次追加到textfile.txt文件。

使用>> file_to_append_to命令追加文件。

例如echo "Hello" >> testFile.txt

注意:如果你只使用一个>,你会覆盖文件的内容。为了确保这种情况不会发生,你可以在你的.bashrc中添加set -o noclobber。

这确保了如果您不小心在现有文件中键入命令> file_to_append_to,它将提醒您该文件已经存在。示例错误信息:文件存在:testFile.txt

因此,当您使用>时,它只允许您创建一个新文件,而不能覆盖现有文件。

当指向文件输出时,使用>>而不是>:

your_command >> file_to_append_to

如果file_to_append_to不存在,则创建该文件。

例子:

$ echo "hello" > file
$ echo "world" >> file
$ cat file 
hello
world

使用>>操作符将文本附加到文件中。