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


当前回答

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

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

在Linux操作系统中,可以使用cat命令将文件内容追加到另一个文件

cat fileName_1.txt >> fileName_2.txt

在前面的命令中,您将把fileName_1.txt的内容追加到fileName_2.txt。

在Windows操作系统中可以使用type命令

type fileName_1.txt >> fileName_2.txt

请看这张gif图片:

使用>> 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