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.
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 number tr '\\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 order join ", "
tells how to join the array elements before passing on to print To summarize answers and comments, this works and maintains spaces:
echo "7, 15, 6, 2, -9" | sed -e $'s:,:\\\\\\n:g' | sort -n | paste -sd ',' - | sed 's:,:, :g'
Note that you may be able to get away with sed -e 's:,:\\n:g'
instead of the first sed
call. This works on my system running bash
version 4.2.46 with sed
version 4.2.2. To remove the spaces (or if they're unnecessary), remove the final sed
call and pipe.
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.