I have some numbers like
7, 15, 6, 2, -9
I want to sort it like this in bash(from command line or either a script file)
-9, 2, 6, 7, 15
How can I do this? I am unable to get this using sort command.
Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.
Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.
echo "7, 15, 6, 2, -9" | sed -e $'s/,/\\\n/g' | sort -n | tr '\n' ',' | sed 's/.$//'
sed -e $'s/,/\\\n/g'
: For splitting string into lines by comma.sort -n
: Then you can use sort by numbertr '\n' ','
: Covert newline separator back to comma.sed 's/.$//'
: Removing tailing comma.Not elegant enough, but it should work :p
With perl
$ s='7, 15, 6, 2, -9'
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$a <=> $b} @F'
-9, 2, 6, 7, 15
$ echo "$s" | perl -F',\h*' -lane 'print join ", ", sort {$b <=> $a} @F'
15, 7, 6, 2, -9
-F',\h*'
use ,
and optional space/tab as field separator
sort {$a <=> $b} @F
sort the array numerically, in ascending order... use sort {$b <=> $a} @F'
for descending orderjoin ", "
tells how to join the array elements before passing on to printIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With