问题
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.
回答1:
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
回答2:
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- see https://perldoc.perl.org/perlrun.html#Command-Switches for explanation of command line options
sort {$a <=> $b} @F
sort the array numerically, in ascending order... usesort {$b <=> $a} @F'
for descending orderjoin ", "
tells how to join the array elements before passing on to print
回答3:
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.
来源:https://stackoverflow.com/questions/47665195/how-to-sort-comma-separated-values-in-bash