0

in a file containing :

...
18-11-2018:othercharacters
10-11-2018:othercharacters
03-10-2018:othercharacters
30-10-2018:othercharacters
27-09-2018:othercharacters
03-12-2018:othercharacters
...

the command :

sort -t- -k2 -k1 

does not sort by date, what am I missing ?

  • 1
    Have you tried the --debug option to see what is happening? – fra-san Dec 3 '18 at 15:16
4

That's one of the reasons why the recommended date format is YYYY-MM-DD.

-k2 sorts on the portion of the line that starts with the second field, you need -k2,2 to sort on the second field only, so:

sort -b -t- -k2,2 -k1,1

Or:

sort -b -k1.7,1.10 -k1.4,1.6 -k1.1,1.2

To sort first on year (7th to 10th character of the first field (counted after having ignored the leading blanks in that field with -b, and with the default field separator (transition from a non-blank to a blank))), then month then day.

  • thanks, just what I needed, and also for clarifying the -k argument – Neo Mosaid Dec 3 '18 at 17:39
  • Or sort -t- -k3n -k2n -k1n. – Isaac Dec 4 '18 at 4:22

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.