Home > bash > sort – using the sort key definition

sort – using the sort key definition

Problem:
You want to sort text and the first column has a date format of MM/DD/YYYY.

Solution:
sort

Example:

$ less infile
04/08/2009CL 84000725014601000000000000095001
03/08/2011C1 84000518101690100000000000036605
01/08/2012C1 84000105201800100000000000001508
05/08/2011CL 84000264701710100000000000017903
01/08/2010C1 84004165015501000000000000266297
07/11/2011C1 84003431101730100000000000002185
03/08/2010CL 84002004015701000000000000091260
12/08/2009CL 84000820015440000000000000240186
08/08/2010CL 84002073016201000000000000140177
02/09/2009C1 84000390014401000000000000035958
11/08/2010C1 84004043016501000000000000043552
infile (END) 

Option 1:

$ sort -bk1.7,1.11 -k1.1,1.5 -k2 infile
02/09/2009 C1 84000390014401000000000000035958
04/08/2009 CL 84000725014601000000000000095001
12/08/2009 CL 84000820015440000000000000240186
01/08/2010 C1 84004165015501000000000000266297
03/08/2010 CL 84002004015701000000000000091260
08/08/2010 CL 84002073016201000000000000140177
11/08/2010 C1 84004043016501000000000000043552
03/08/2011 C1 84000518101690100000000000036605
05/08/2011 CL 84000264701710100000000000017903
07/11/2011 C1 84003431101730100000000000002185
01/08/2012 C1 84000105201800100000000000001508

Option 2:

$ sort -nb +0.6 -0.10 +0.0 -0.2 +0.3 -0.5 infile
02/09/2009 C1 84000390014401000000000000035958
04/08/2009 CL 84000725014601000000000000095001
12/08/2009 CL 84000820015440000000000000240186
01/08/2010 C1 84004165015501000000000000266297
03/08/2010 CL 84002004015701000000000000091260
08/08/2010 CL 84002073016201000000000000140177
11/08/2010 C1 84004043016501000000000000043552
03/08/2011 C1 84000518101690100000000000036605
05/08/2011 CL 84000264701710100000000000017903
07/11/2011 C1 84003431101730100000000000002185
01/08/2012 C1 84000105201800100000000000001508

Source:
http://www.unix.com/shell-programming-scripting/202933-sorting-data-files-based-column-having-date-value-mm-dd-yyyy-format.html

Advertisements
Categories: bash Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s