[英]How can I 'echo' out things without a newline?
I have the following code:我有以下代码:
for x in "${array[@]}"
do
echo "$x"
done
The results are something like this (I sort these later in some cases):结果是这样的(我稍后在某些情况下对这些进行排序):
1
2
3
4
5
Is there a way to print it as 1 2 3 4 5
instead?有没有办法将其打印为
1 2 3 4 5
代替? Without adding a newline every time?无需每次都添加换行符?
Yes.是的。 Use the
-n
option:使用
-n
选项:
echo -n "$x"
From help echo
:从
help echo
:
-n do not append a newline
-n 不附加换行符
This would strips off the last newline too, so if you want you can add a final newline after the loop:这也会去掉最后一个换行符,所以如果你愿意,你可以在循环之后添加最后一个换行符:
for ...; do ...; done; echo
Note:笔记:
This is not portable among various implementations of echo
builtin/external executable.这在
echo
内置/外部可执行文件的各种实现中是不可移植的。 The portable way would be to use printf
instead:可移植的方法是使用
printf
代替:
printf '%s' "$x"
printf '%s\n' "${array[@]}" | sort | tr '\n' ' '
printf '%s\n'
-- 比echo
更健壮,并且为了sort
的缘故,您希望在此处使用换行符"${array[@]}"
-- 对您的特定数组而言,引号是不必要的,但这是一种很好的做法,因为您不需要通常需要在那里进行分词和全局扩展
You don't need a for loop to sort numbers from an array.您不需要for循环来对数组中的数字进行排序。
Use process substitution like this:像这样使用进程替换:
sort <(printf "%s\n" "${array[@]}")
To remove new lines, use:要删除新行,请使用:
sort <(printf "%s\n" "${array[@]}") | tr '\n' ' '
You can also do it this way:你也可以这样做:
array=(1 2 3 4 5)
echo "${array[@]}"
如果出于某种原因, -n
不能为您解决此问题,您还可以将\c
添加到要回显的内容的末尾:
echo "$x\c"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.