在同一行 Bash 上排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19274695/
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
Sorting on Same Line Bash
提问by Tom Gorski
Hello I am trying to sort a set of numeric command line arguments and then echo them back out in reverse numeric order on the same line with a space between each. I have this loop:
您好,我正在尝试对一组数字命令行参数进行排序,然后在同一行中以相反的数字顺序将它们回显出来,每个参数之间有一个空格。我有这个循环:
for var in "$@"
do
echo -n "$var "
done | sort -rn
However when I added the -n
to the echo the sort
command stops working. I am trying to do this without using printf
. Using the echo -n
they do not sort and simply print in the order they were entered.
但是,当我将 the 添加-n
到 echo 时,sort
命令停止工作。我正在尝试不使用printf
. 使用echo -n
它们不排序,只是按照输入的顺序打印。
回答by anubhava
You can do it like this:
你可以这样做:
a=( $@ )
b=( $(printf "%s\n" ${a[@]} | sort -rn) )
printf "%s\n" ${b[@]}
# b is reverse sorted nuemrically now
回答by devnull
man sort
would tell you:
man sort
会告诉你:
sort - sort lines of text files
So you can transform the result into the desired format aftersorting.
所以你可以在排序后将结果转换为所需的格式。
In order to achieve the desired result, you can say:
为了达到预期的结果,您可以说:
for var in "$@"
do
echo "$var"
done | sort -rn | paste -sd' '
回答by Cole Tierney
One trick is to play with the IFS:
一个技巧是玩 IFS:
IFS=$'\n'
set "$*"
IFS=$' \n'
set $(sort -rn <<< "$*")
echo $*
This is the same idea but easier to read with the join() function:
这是相同的想法,但使用 join() 函数更容易阅读:
join() {
IFS=
shift
echo "$*"
}
join ' ' $(join $'\n' $* | sort -nr)
回答by matteoeghirotta
Maybe that's because sort is "line-oriented", so you need every number on a separate line, which is not the case using -n with echo. You could simply put the sorted numbers back in one line using sed, like that:
也许这是因为 sort 是“面向行的”,因此您需要将每个数字都放在单独的行上,而将 -n 与 echo 结合使用则不是这种情况。您可以简单地使用 sed 将排序后的数字放回一行,如下所示:
for var in "$@";
do
echo "$var ";
done | sort -rn | sed -e ':a;N;s/\n/ /;ba'
回答by zakinster
sort
is used to sort multiple lines of text. Using the option -n
of echo
, you are printing everything in one line.
If you want the output to be sorted, you have to print it in multiple lines :
sort
用于对多行文本进行排序。使用选项-n
中echo
,你是在一行中打印的一切。如果要对输出进行排序,则必须将其打印成多行:
for var in "$@"
do
echo $var
done | sort -rn
If you want the result on only one line you could do :
如果你只想要一行的结果,你可以这样做:
echo $(for var in "$@"; do echo $var; done | sort -rn)