1

I am trying to sort a file as following which has multiple columns, separated with comma, and one of the column has date with the following format mm/dd/yyyy.

$cat filename

AN1143,45.7,03/05/2012,
H9477,45.3,01/15/2010,
DN1222,45.1,03/05/1800,
J960,26.7,06/02,1990,
Z959,28.2,03/21/2016,
H12421,27.7,06/21/2000

My intention is to sort first based on the first column and then the third column which has the date. I tried the following command:

sort -t"," -k1,1 -k3,9n.3,10n -k3,1n.3,2n -k3,4n.3,5n filename 

but I faced this error any help with explanation is appreciated.

sort: stray character in field spec: invalid field specification â3,9n.3,10nâ

  • can you edit the question and add the result you seek after ? – Wissam Roujoulah Nov 28 '16 at 16:35
  • 1
    -k3,9n.3,10n looks to have the comma and period (dot, full stop) characters interchanged. – icarus Nov 28 '16 at 16:43
6

Try this instead:

sort -t, -k1,1 -k3.7n -k3.1,3.2n -k3.4,3.5n < filename
  • There's no need to quote the comma delimiter
  • The first sort-key definition uses column 1
  • The second sort-key definition uses column 3's "year" field, sorted numerically
  • The third sort-key uses column 3's "month" field, sorted numerically
  • The fourth sort-key uses column 3's "day" field, sorted numerically

Sample run with an enhanced sample data file, showing the sorting:

Input:

AN1143,45.7,03/05/2012,
AN1143,45.7,02/05/2012,
AN1143,45.7,03/04/2012,
AN1143,45.7,03/05/2011,
H9477,45.3,01/15/2010,
DN1222,45.1,03/05/1800,
J960,26.7,06/02,1990,
Z959,28.2,03/21/2016,
H12421,27.7,06/21/2000

Output:

AN1143,45.7,03/05/2011,
AN1143,45.7,02/05/2012,
AN1143,45.7,03/04/2012,
AN1143,45.7,03/05/2012,
DN1222,45.1,03/05/1800,
H12421,27.7,06/21/2000
H9477,45.3,01/15/2010,
J960,26.7,06/02,1990,
Z959,28.2,03/21/2016,
  • 2
    in GNU sort, add the --debug flag to see the sorting decisions (lines top to bottom indicate the key that was used and in what order) – Jeff Schaller Nov 28 '16 at 16:48
  • Thanks a lot Jeff. what about if I want to keep the same sorting but have the earliest date first and the latest date after (like reverse of the current date sorting )? – Daniel Nov 28 '16 at 16:52
  • I'm confused by "keep the same sorting" and "change the current sorting" :) it's already 'earliest date first', after sorting on column 1... – Jeff Schaller Nov 28 '16 at 17:04
  • 1
    @Daniel just append an r to the column-3 sort-keys; for example, -k3.7nr – Jeff Schaller Nov 28 '16 at 17:18
  • 1
    Different brains work differently, and many solutions all work, which is what I love about POSIX (: – DopeGhoti Nov 28 '16 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.