Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting on Same Line Bash

Tags:

bash

unix

sorting

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.

like image 941
Tom Gorski Avatar asked Sep 16 '25 07:09

Tom Gorski


1 Answers

You can do it like this:

a=( $@ )
b=( $(printf "%s\n" ${a[@]} | sort -rn) )

printf "%s\n" ${b[@]}
# b is reverse sorted nuemrically now
like image 130
anubhava Avatar answered Sep 17 '25 22:09

anubhava