How do I sort files by date in filename?

1

I have a set of filenames like this

vorlesung 02.11.15.mp4
vorlesung 04.01.16.mp4
vorlesung 07.12.15.mp4
vorlesung 09.11.15.mp4
vorlesung 09.12.15.mp4
...

The last part of the file name is a date in european format. Now I attempt to sort these according to date with sort (since awk and stuff seems over the top for this). From this answer I concluded that something like this should work.

ls *.mp4 | sort -k 2.7,2.8 -k 2.4,2.5 -k 2.1,2.3

But in reality, only the key 2.1,2.3 seems to do something. When I apply the others separately, nothing happens. The numeric-sort flag does not help. What is the right syntax here?

oarfish

Posted 2016-03-02T12:39:21.313

Reputation: 309

Answers

1

Well... awk not necessarily must be cast away here. We can use it to prepend our file names with the expression by which we want the sort and after the sort is done, just ignore the prefix.

$ cat lst
vorlesung 02.11.15.mp4
vorlesung 04.01.16.mp4
vorlesung 07.12.15.mp4
vorlesung 09.11.15.mp4
vorlesung 09.12.15.mp4
$ awk -F'[ .]' '{print $4 $2 $3, $0}' lst | sort | sed -e 's/^[0-9]* //'
vorlesung 02.11.15.mp4
vorlesung 07.12.15.mp4
vorlesung 09.11.15.mp4
vorlesung 09.12.15.mp4
vorlesung 04.01.16.mp4

Gombai Sándor

Posted 2016-03-02T12:39:21.313

Reputation: 3 325

You mixed up the print args though, it should be print $4 $3 $3, $0 for the desired result. – oarfish – 2016-03-03T17:43:22.730

That would mean comparing YY.MM.MM that is the day would have no role, but I'm fine with that. – Gombai Sándor – 2016-03-03T18:05:29.823

Whoops, I meant print $4 $3 $2, $0 for year, month, day. – oarfish – 2016-03-03T18:07:41.970

Ah, I see... the background is: in Hungary, we use the same ordering as defined by ANSI (YMD). In other cases I cannot be sure if MDY or DMY is used if neither day nor month is above 12. Both would be valid depending on the country, and I missed the bull's eye, however I should have seen your intention in your key definitions in the question. – Gombai Sándor – 2016-03-03T20:25:26.657