I'm trying to use the sort command (5.97) to sort one column of data and then another.

Right now, I'm doing:

 > ls test/2/*.jpg | sort -t- -k1 -g -s
test/2/0-0.jpg
test/2/0-10.jpg
test/2/0-1.jpg
test/2/0-2.jpg
test/2/0-3.jpg
test/2/0-4.jpg
test/2/0-5.jpg
test/2/0-6.jpg
test/2/0-7.jpg
test/2/0-8.jpg
test/2/0-9.jpg
test/2/1-0.jpg
test/2/1-10.jpg
test/2/1-1.jpg
test/2/1-2.jpg
test/2/1-3.jpg
test/2/1-4.jpg
test/2/1-5.jpg
test/2/1-6.jpg
test/2/1-7.jpg
test/2/1-8.jpg
test/2/1-9.jpg
test/2/2-0.jpg
test/2/2-10.jpg
test/2/2-1.jpg
test/2/2-2.jpg
test/2/2-3.jpg
test/2/2-4.jpg
test/2/2-5.jpg
test/2/2-6.jpg
test/2/2-7.jpg
test/2/2-8.jpg
test/2/2-9.jpg

But as you can see, the two digit numbers are in the wrong spot. Is there a way to do this with sort?

link|improve this question
feedback

2 Answers

Add a "-k2" after your "-k1". I.e.

ls test/2/*.jpg | sort -t- -k1 -k2 -g -s   (or sort -t- -n -k1 -k2)

If there's a conflict, it'll use the 2nd field (-k2) to resolve and (well, I use) the -n treats them as numbers. If you were to switch the order and put -k2 -k1, it would sort by the second number in filename and use the first one only when there's a conflict.

link|improve this answer
both ls test/2/*.jpg | sort -t- -k1 -k2 -g -s and ls test/2/*.jpg | sort -t- -k2 -k1 -g -s give me the same result: test/2/0-0.jpg test/2/1-0.jpg test/2/2-0.jpg test/2/3-0.jpg test/2/4-0.jpg test/2/5-0.jpg test/2/0-1.jpg test/2/1-1.jpg test/2/2-1.jpg test/2/3-1.jpg test/2/4-1.jpg test/2/5-1.jpg etc. I want it to be the other way. – tkerwin Jan 19 '10 at 21:30
Try sort -t- -n -k1 -k2 to ensure your fields are getting interpreted as numbers. Both answers posted so far have mentioned this. – DaveParillo Jan 19 '10 at 21:52
-n gives the same result – tkerwin Jan 19 '10 at 22:20
feedback

hey, the reason why it is not getting sorted is because, the sort command is not able to identify any numbers in each line. It considers it as a strings. Try running the same command with the suffix .jpg removed. You will get the order that you intend. Refer, http://www.softpanorama.org/Tools/sort.shtml . In this link read the Ordering options section (-n option). Hope this solves your problem.

link|improve this answer
+1, but you don't have to strip off the extension to get a sort firld to be interpreted as numeric. – DaveParillo Jan 19 '10 at 21:54
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.