4

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
...
12

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

4

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/-./-/'
1

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.

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.