bash 如何将字符串附加到同一行而不是创建新行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12297820/
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 strings to the same line instead of creating a new line?
提问by John Threepwood
Redirection to a file is very usefull to append a string as a new line to a file, like
重定向到文件对于将字符串作为新行附加到文件非常有用,例如
echo "foo" >> file.txt
echo "bar" >> file.txt
Result:
结果:
foo
bar
But is it also possible to redirect a string to the same line in the file ?
但是是否也可以将字符串重定向到文件中的同一行?
Example:
例子:
echo "foo" <redirection-command-for-same-line> file.txt
echo "bar" <redirection-command-for-same-line> file.txt
Result:
结果:
foobar
回答by cnicutar
The newline is added by echo
, not by the redirection. Just pass the -n
switch to echo
to suppress it:
换行符由echo
,而不是由重定向添加。只需通过-n
开关echo
来抑制它:
echo -n "foo" >> file.txt
echo -n "bar" >> file.txt
-n
do not output the trailing newline
-n
不输出尾随换行符
回答by xiphos71
An alternate way to echo results to one line would be to simply assign the results to variables. Example:
将结果回显到一行的另一种方法是简单地将结果分配给变量。例子:
j=$(echo foo)
i=$(echo bar)
echo $j$i
foobar
echo $i $j
bar foo
This is particularly useful when you have more complex functions, maybe a complex 'awk' statement to pull out a particular cell in a row, then pair it with another set.
当您有更复杂的函数时,这特别有用,可能是一个复杂的“awk”语句来连续拉出特定单元格,然后将它与另一个集合配对。