在Linux中,向文件追加文本的最简单方法是什么?
我看过at this question,但公认的答案是使用了一个额外的程序(sed
)我相信应该有一种更简单的方法使用echo
或类似的程序。
发布于 2013-07-17 22:11:51
cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter.
^D
从本质上讲,您可以将任何想要的文本转储到文件中。CTRL-D发送一个文件结束信号,该信号终止输入并返回到shell。
发布于 2015-06-11 00:01:59
另一种可能的方法是:
echo "text" | tee -a filename >/dev/null
-a
将附加到文件的末尾。
如果需要sudo
,请使用:
echo "text" | sudo tee -a filename >/dev/null
发布于 2017-04-15 15:59:02
跟进已接受的答案。
您需要的不是CTRL-D to designate the end if using this in a script。试着这样做:
cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF
这会将文本附加到指定的文件中(不包括"EOF")。
它利用了一个here document (or heredoc)。
但是,如果您需要sudo来附加到指定的文件,那么如果您直接在命令行上输入,那么由于I/O重定向,您将在使用line文档时遇到问题。
当您直接在命令行上键入时,此变体将起作用:
sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'
或者,您可以改用tee
,以避免在使用heredoc和cat时出现的命令行sudo问题:
tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF
https://stackoverflow.com/questions/17701989
复制相似问题