0

I'm trying to sort the following file by date with earliest to latest: $NAME DIA

# Date,Open,High,Low,Close,Volume,Adj Close
01-10-2014,169.91,169.98,167.42,167.68,11019000,167.68
29-04-2014,164.62,165.27,164.49,165.00,4581400,163.40
17-10-2013,152.11,153.59,152.05,153.48,9916600,150.26
06-09-2013,149.70,149.97,147.77,149.09,9001900,145.68
02-11-2012,132.56,132.61,130.47,130.67,5141300,125.01
01-11-2012,131.02,132.44,130.97,131.98,3807400,126.27

sort -t- -k3 -k2 -k1 DIA.txt gets the year right but scrambles the month and day.

any help would be greatly appreciated.

1
  • 1
    Can you show an example of what the result you got was vs what you expected? Commented Oct 2, 2014 at 19:16

3 Answers 3

1

This seems to produce correct output

sort -s -t- -k3,3 -k2,2 -k1,1

output:

$ sort -s -t- -k3,3 -k2,2 -k1,1 dia.txt
# Date,Open,High,Low,Close,Volume,Adj Close
01-11-2012,131.02,132.44,130.97,131.98,3807400,126.27
02-11-2012,132.56,132.61,130.47,130.67,5141300,125.01
06-09-2013,149.70,149.97,147.77,149.09,9001900,145.68
17-10-2013,152.11,153.59,152.05,153.48,9916600,150.26
29-04-2014,164.62,165.27,164.49,165.00,4581400,163.40
01-10-2014,169.91,169.98,167.42,167.68,11019000,167.68
Sign up to request clarification or add additional context in comments.

1 Comment

You may want to include the sorted output showing the output produced. I'll do it for you this time.
0

I would try changing the date format first.

sed -r "s/(..)-(..)-(....)/\\3-\\2-\\1/" DIA.txt | sort

You can also change it back after sorting the lines.

sed -r "s/(..)-(..)-(....)/\\3-\\2-\\1/" DIA.txt | sort | sed -r "s/(....)-(..)-(..)/\\3-\\2-\\1/"

Comments

0

sort's -k flag only allows you to specify two columns that give the range of keys to use in the sort. Here you want to involve a third column before that. There is a special syntax to use an additional column to resolve ties (here between rows when sorting with column 3 and 2):

sort -t'-' -k3,2.1 d

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.