tags:

views:

34

answers:

3

What's the easiest way to sort a comma separated list of values in Mac OS X:

Input: "a, b, aaa, bc"

Output: "a, aaa, b, bc"

I'd like to do this from the terminal so that I can pipe the output to another command.

+2  A: 
$ echo "a, b, Aaa, bc" |egrep -o "[^, ]+" |sort -f | xargs |sed -e 's/ /, /g'

if the values contain spaces:

$ echo "a, b, Aaa, bc" |egrep -o "[^, ][^,]*" |sort -f | xargs -I Q echo Q, | xargs

but then you get an extra ", " for free at the end.

mvds
That's cool, I didn't know about xargs.
Abdullah Jibaly
`man xargs` is good reading, and connecting it to `find -print0` is also good basic knowledge.
mvds
+1  A: 
echo "a, b, Aaa, bc"|tr -s "[, ]" "\n"|sort|sed -e :a -e 'N;s/\n/,/;ba'

echo "a, b, Aaa, bc"| tr -s "[, ]" "\n"|sort|tr "\n" ","|sed 's/,$//'
ghostdog74
There's something going wrong in the sed portion, I like the use of tr though.
Abdullah Jibaly
see another method in my edit
ghostdog74
almost there, except it's losing the space after the comma.
Abdullah Jibaly
A: 
echo 'a, b, aaa, bc' | awk '{split($0, a, ", "); n = asort(a); for (i=1; i<=n; i++) {printf a[i]; if (i<n) printf ", "}}'
Dennis Williamson