简体   繁体   中英

Sorting on Same Line Bash

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.

You can do it like this:

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

printf "%s\n" ${b[@]}
# b is reverse sorted nuemrically now

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 :

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)

man sort would tell you:

   sort - sort lines of text files

So you can transform the result into the desired format after sorting.

In order to achieve the desired result, you can say:

for var in "$@"
do
  echo "$var"
done | sort -rn | paste -sd' '

One trick is to play with the IFS:

IFS=$'\n'
set "$*"
IFS=$' \n'
set $(sort -rn <<< "$*")
echo $*

This is the same idea but easier to read with the join() function:

join() {
    IFS=$1
    shift
    echo "$*"
}

join ' ' $(join $'\n' $* | sort -nr)

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:

for var in "$@";
do
    echo "$var ";
done | sort -rn | sed -e ':a;N;s/\n/ /;ba'

Sorting numbers in single line either comma, or space seperated, use the below

 echo "12,12,3,55,567,23,6,9,35,423"|sed -e 's;[ |,];\n;g'|sort -n|xargs|sed -e 's; ;,;g'

if your output does not need comma, skip the sed after xargs

No loops required:

#!/bin/bash
sorted=( $(sort -rn < <(printf '%s\n' $@)) )
echo ${sorted[@]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM