bash 如何在没有换行符的情况下回显内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38021348/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:20:24  来源:igfitidea点击:

How to echo out things without a newline?

bash

提问by ricky162

I have the following code...

我有以下代码...

for x  in ${array[@]}
               do
                  echo $x
               done| sort

The results are something like this

结果是这样的

1
2
3
4
5

Is there a way to print it as 1 2 3 4 5instead? Without adding a newline every time?

有没有办法把它打印出来1 2 3 4 5?每次都不添加换行符?

I also tried printfas suggested by another post, but it's still printing new lines

我也printf按照另一篇文章的建议尝试过,但它仍在打印新行

for x  in ${array[@]}
               do
                  printf '%s' "$x"
               done| sort

回答by heemayl

Yes. Use the -noption:

是的。使用-n选项:

 echo -n $x

From help echo:

来自help echo

-n  do not append a newline

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 echobuiltin/external executable. The portable way would be to use printfinstead:

这在echo内置/外部可执行文件的各种实现中是不可移植的。可移植的方式是使用printf

printf '%s' "$x"

回答by anubhava

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' ' '

回答by PSkocik

printf '%s\n' "${array[@]}" | sort |tr '\n' ' '

printf '%s\n'-- more robust than echoand you want the newlines here for sort's sake "${array[@]}"-- quotes unnecessary for your particular array, but good practice as you don't generally want word-spliting and glob expansions there

printf '%s\n'-比更强大的echo,你想在这里为新行sort的缘故 "${array[@]}"-不必要的报价为您的特定阵列,但良好的做法,你不一般要字的分裂和水珠扩张有