Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a text file in following format, and I need to sort the lines according to date. Is there some simple way to do it (preferably in bash) ?

2013-May-30     2
2013-May-21     10
2013-Jun-27     8
2013-Jun-18     9
2013-Jun-09     17
2013-May-20     21
2013-Jun-10     1
2013-Jun-01     2
2013-Aug-09     6
2013-Aug-08     5
2013-Aug-07     2
...
share|improve this question

3 Answers 3

up vote 8 down vote accepted

If you tell GNU sort to split the fields by a different character, a dash - in your case it's pretty easy to sort this:

$ sort -n -t"-" -k1 -k2M -k3 file.txt

Example

$ sort -n -t"-" -k1 -k2M -k3 file.txt
2013-May-20     21
2013-May-21     10
2013-May-30     2
2013-Jun-01     2
2013-Jun-09     17
2013-Jun-10     1
2013-Jun-18     9
2013-Jun-27     8
2013-Aug-07     2
2013-Aug-08     5
2013-Aug-09     6

Reference

share|improve this answer

If your sort is not the GNU sort and doesn't support sorting by month names, you'd need to convert those month names to something your sort can sort on:

sed 's/$/-Jan1Feb2Mar3Apr4May5Jun6Jul7Aug8Sep9Oct10Nov11Dec12/
     s/-\(...\)\(.*\)-.*\1\([0-9]*\)[^-]*$/-\3\1\2/' |
  sort -nt- -k1 -k2 -k3 |
  sed 's/-./-/'
share|improve this answer

Yes there is. You can do something like:

sort -k 2,2n -k 3
Sort data using the given column number. The option -k 2,2n -k 3 sorts each column. First, it will sort 2nd column (date mm field) and then 3rd column (day).

More info can be found here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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