Reputation: 4495
I want to be able to list all files within a directory sorted by multiple sort keys. For example:
Level_5_10_1.jpg
Level_5_1_1.jpg
I want Level_5_1_1.jpg
to show up first. The sort order should start from the last number, so:
Level_4_2_1.jpg > Level_4_1_10.jpg
Level_3_2_1.jpg > Level_3_1_10.jpg
and so on..
I tried:
ls | sort -h -k3,3n -k2,2n -k1,1n -t_
but didn't get the result I wanted. For example, it listed Level_5_1_2.jpg < Level_1_2_1.jpg
which is incorrect
Any ideas?
PS: This is a pastebin of the file list.
Upvotes: 3
Views: 106
Reputation: 46856
From your description, I think I'm getting the right results from this:
$ ls | sort -nt_ -k4,4 -k3,3 -k2,2
Remember that your first field (-k1
) is the word "Level" in the files you've included in your question.
If you have really complex sorting needs, of course, you can always "map" your criteria onto simpler sortable items. For example, if your sort
didn't include a -k
option, you might do this:
$ ls | awk '{printf "%2d %2d %2d %s\n", $4, $3, $2, $0}' FS="[_.]" - | sort -n | awk '{print $NF}'
This takes the important fields, translates them in prefixed digits, sorts, then prints only the filename. You could use this technique if you wanted to map weekdays, or months, or something that doesn't sort naturally.
Of course, all this suffers from the standard set of ParsingLS issues.
Upvotes: 0
Reputation: 1761
I've taken a small sample of filenames. When you split the filenames by _
with the -t
option, the first field is 1 which would be "Level", field 2 would be the first number and so on. I'm not entirely sure of the order that you are specifically after, but I think this solution should at least provide you with something to work with. Note that I have truncated some of the results so that the overall pattern can hopefully be viewed more easily.
me@machine:~$ ls Level*.jpg | sort -t_ -k2n -k3n -k4n
Level_1_1_1.jpg
Level_1_1_2.jpg
Level_1_1_3.jpg
Level_1_1_4.jpg
Level_1_1_5.jpg
Level_1_2_1.jpg
Level_1_2_2.jpg
Level_1_2_3.jpg
Level_1_2_4.jpg
Level_1_2_5.jpg
Level_1_3_1.jpg
...
Level_1_10_5.jpg
Level_2_1_1.jpg
...
Level_2_1_5.jpg
Level_2_2_1.jpg
...
Level_2_2_5.jpg
Level_2_3_1.jpg
...
Level_2_10_5.jpg
Level_3_1_1.jpg
Upvotes: 1