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


当前回答

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

其他回答

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

your_command >> file_to_append_to

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

例子:

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

例如,你的文件包含:

 1.  mangesh@001:~$ cat output.txt
    1
    2
    EOF

如果你想在文件末尾追加,那么---->记住'text' >> 'filename'之间的空格

  2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 
    1
    2
    EOF
    somthing to append

和覆盖文件的内容:

  3.  mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
    somthing new to write

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

一个更快的选择可能是:

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

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

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

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

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

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