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


当前回答

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

>表示覆盖

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

其他回答

我建议你做两件事:

在shell脚本中使用>>将内容附加到特定文件。文件名可以固定,也可以使用某种模式。 设置一个每小时一次的cronjob来触发shell脚本

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

your_command >> file_to_append_to

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

例子:

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

要追加一个文件,请使用>>

echo "hello world"  >> read.txt   
cat read.txt     
echo "hello siva" >> read.txt   
cat read.txt

那么输出应该是

hello world   # from 1st echo command
hello world   # from 2nd echo command
hello siva

要覆盖文件,请使用>

echo "hello tom" > read.txt
cat read.txt  

那么输出是

你好,汤姆

虽然所有这些答案在技术上都是正确的,但通常情况下,使用>>追加到文件中是正确的方法,但请注意,如果在例如解析/处理文件时在循环中使用此方法,并将每行追加到结果文件中,则这可能比您预期的要慢得多。

一个更快的选择可能是:

stringBuilder=""
while read -r line; do
  # $'\n' prints a newline so we don't have to know what special chars the string contains
  stringBuilder+="$line"$'\n'
done < "myFile.txt"
echo "$stringBuilder" > $file

警告:您正在将所有行读入内存;内存是一种有限的资源,所以不要对巨大的文件这样做。

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