Echo Appending Text [duplicate]

北城以北 提交于 2020-08-11 07:19:13

问题


If I'm in terminal and I write some basic string to a file, is there a way to continually append to that file using echo?

For instance, echo 'hello' > file will put 'hello' into that file, but what if I now want to append ' world' to file? I know that if I do echo ' world', it'll overwrite the first string I wrote into file. Is there any += operator I can use in bash?

EDIT: Nevermind, I can append using >>. Is it possible to append to the same line instead of to a new line?


回答1:


echo -n 'Hello' > file
echo ', World!' >> file

The >> redirection operator means "append."

Here we're using a non-standard extension of echo, where -n tells it not to append a new line.

If you want standard-compliant behavior, use printf:

printf 'Hello' > file
printf ', World!\n' >> file

Edit: using double quote around a string containing the exclamation ! may not work with some versions. It could get interpreted as a history expansion token. Use single quotes to prevent this.



来源:https://stackoverflow.com/questions/43675379/echo-appending-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!