Help with sort command

I have a file with the following content:-

181268525,0640613864,B,113,22-dec-2011 14:12:08,
181268525,0640613864,C,113,25-dec-2011 14:18:50,
181268525,0640613864,L,113,26-dec-2011 14:07:46,
181268525,0640613864,X,113,01-jan-2012 16:57:45,
181268525,0640613864,X,113,04-jan-2012 14:13:27,
181268525,0640613864,X,113,29-dec-2011 14:04:12,
181268525,0640613864,Y,113,02-jan-2012 13:58:08,
181268525,0640613864,Y,113,05-jan-2012 14:14:18,
181268525,0640613864,Y,113,08-jan-2012 14:11:43,

I am running the sort command on this file to sort by the date, but somehow I am not getting the expected results:-

cat test | sort -t',' -k 5.10,5.14 -k 5.15,5.18M -k 5.19,5.20
181268525,0640613864,B,113,22-dec-2011 14:12:08,
181268525,0640613864,X,113,29-dec-2011 14:04:12,
181268525,0640613864,L,113,26-dec-2011 14:07:46,
181268525,0640613864,C,113,25-dec-2011 14:18:50,
181268525,0640613864,Y,113,02-jan-2012 13:58:08,
181268525,0640613864,Y,113,05-jan-2012 14:14:18,
181268525,0640613864,X,113,04-jan-2012 14:13:27,
181268525,0640613864,Y,113,08-jan-2012 14:11:43,
181268525,0640613864,X,113,01-jan-2012 16:57:45,

01-jan-2012 is appearing after 08-jan-2012. Please assist.

Because you are sorting on these values:

11 14,12,08
11 14,04,12
11 14,07,46
11 14,18,50
12 13,58,08
12 14,14,18
12 14,13,27
12 14,11,43
12 16,57,45

The month in your data file is in short name format, so it will be hard to use sort to get it in proper date order. Have you considered numeric format for the month?

If you're stuck with that format you might have to do something horrible like this:

sed \
-e 's/-jan-/-01jan-/' \
-e 's/-feb-/-02feb-/' \
-e 's/-mar-/-03mar-/' \
-e 's/-apr-/-04apr-/' \
-e 's/-may-/-05may-/' \
-e 's/-jun-/-06jun-/' \
-e 's/-jul-/-07jul-/' \
-e 's/-aug-/-08aug-/' \
-e 's/-sep-/-09sep-/' \
-e 's/-oct-/-10oct-/' \
-e 's/-nov-/-11nov-/' \
-e 's/-dec-/-12dec-/' test | sort -t, -k 5.12,5.13 -k 5.4,5.5 -k 5.1,5.2 -k 5.15,5.22 | sed \
-e 's/-01jan-/-jan-/' \
-e 's/-02feb-/-feb-/' \
-e 's/-03mar-/-mar-/' \
-e 's/-04apr-/-apr-/' \
-e 's/-05may-/-may-/' \
-e 's/-06jun-/-jun-/' \
-e 's/-07jul-/-jul-/' \
-e 's/-08aug-/-aug-/' \
-e 's/-09sep-/-sep-/' \
-e 's/-10oct-/-oct-/' \
-e 's/-11nov-/-nov-/' \
-e 's/-12dec-/-dec-/'
1 Like

Thanks, that helped :slight_smile:

Oh I didn't pick up on you using the M option with sort.

If your sort supports month sorting then the following will work too:

sort -t, -k 5.8,5.11 -k 5.4,5.6M -k 5.1,5.2 -k 5.13,5.20 test
08-jan-2012 14:11:43
   | | |  | |      |
   4 6 8 11 13     20