How to sort comma separated values in bash?

Issue

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.

Solution

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

Answered By – Yu-Lin Chen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published