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


当前回答

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

>表示覆盖

$ 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
  >>

其他回答

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

your_command >> file_to_append_to

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

例子:

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

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

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

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

我会使用printf而不是echo,因为它更可靠,并且正确地处理诸如new line \n之类的格式。

这个例子产生一个类似于前面例子中的echo的输出:

printf "hello world"  >> read.txt   
cat read.txt
hello world

然而,如果你在这个例子中用echo替换printf, echo会把\n当作一个字符串,从而忽略意图

printf "hello\nworld"  >> read.txt   
cat read.txt
hello
world

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

>表示覆盖

$ 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
  >>

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