Linux 如何使用 shell 脚本在文件中附加多行文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4990172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append several lines of text in a file using a shell script
提问by Yrgl
I want to write several lines (5 or more) to a file I'm going to create in script. I can do this by echo >> filename
. But I would like to know what the best way to do this?
我想将几行(5 行或更多行)写入我将在脚本中创建的文件。我可以做到这一点echo >> filename
。但我想知道这样做的最佳方法是什么?
采纳答案by Paused until further notice.
You can use a here document:
您可以使用此处的文档:
cat <<EOF >> outputfile
some lines
of text
EOF
回答by Robert Hensing
I usually use the so-called "here-document" Dennis suggested. An alternative is:
我通常使用 Dennis 建议的所谓“here-document”。另一种选择是:
(echo first line; echo second line) >> outputfile
This should have comparable performance in bash, as (....) starts a subshell, but echo is 'inlined' - bash does not run /bin/echo, but does the echo by itself.
这应该在 bash 中具有可比的性能,因为 (....) 启动一个子shell,但是 echo 是“内联的” - bash 不运行 /bin/echo,而是自己执行 echo。
It might even be faster because it involves no exec().
它甚至可能更快,因为它不涉及 exec()。
This style is even more useful if you want to use output from another command somewhere in the text.
如果您想在文本中某处使用另一个命令的输出,这种样式甚至更有用。