Sort comma-separated fields on each line by numeric value

sorttext processing

I tried this:

$ echo "2,3435,1" | sort -n
2,3435,1

$ sort -t',' -n test_sort.txt
kill,gill,burger
110,20,30,13

$ cat test_sort.txt
110,20,30,13
kill,gill,burger

Why doesn't my sort command work?

My desired sort command should work like this:

$sort -t',' -n test_sort.txt  
110,13,20,30,burger,gill,kill

ANSWER : tr , '\n' < a | sort -n | paste -sd, –

"Thanks to Stéphane Chazelas"

Best Answer

sort operates on entire lines. By default, it sorts on the entire contents of that line, but -k can be used to sort on one or more fields within those lines. -t can be used to change the delimiter between fields. I can't think of a case where using -t without also using -k makes any sense.

Your second command, which is equivalent to:

printf "%s\n%s\n" "110,20,30,13" "kill,gill,burger" | sort -t',' -n

produces:

kill,gill,burger
110,20,30,13

Which is what I'd expect. -t',' has no effect because it's changing the field delimiter when you haven't told sort to operate on individual fields, and so k is sorted before 1 because its numerical value is 0 (and you requested numerical ordering using -n).

Related Question