GNU sort command to accurately sort dates on multiple fields

Let's say you've got an ugly set of dates which are inconsistently padded with zeroes:

$ cat dates
1
2
3
4
5
6
7
8
9
10
2/3/2011
02/02/2011
02/01/2011
12/3/2010
2/3/2011
01/03/2011
12/02/2010
01/02/2011
12/1/2010
1/1/2011

Using forward slash as the delimiter, we tell sort to sort on the third field first (year), then on the first field (month) and finally on the second field (day):

$ cat dates | sort -t/ -k 3n -k 1n -k 2n
1
2
3
4
5
6
7
8
9
10
12/1/2010
12/02/2010
12/3/2010
1/1/2011
01/02/2011
01/03/2011
02/01/2011
02/02/2011
2/3/2011
2/3/2011

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).