简体   繁体   中英

How to sort comma separated values in bash?

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/.$//'
  1. sed -e $'s/,/\\\\\\n/g' : For splitting string into lines by comma.
  2. sort -n : Then you can use sort by number
  3. tr '\\n' ',' : Covert newline separator back to comma.
  4. 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.

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