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


当前回答

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

要测试这个,请运行:

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

这样做几次,然后运行:

cat textfile.txt

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

其他回答

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

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  

那么输出是

你好,汤姆

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

要测试这个,请运行:

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

这样做几次,然后运行:

cat textfile.txt

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

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

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

your_command >> file_to_append_to

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

例子:

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

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