1

I am trying to sort a file by a date field. I realize this has been done before, however, I cannot find an example that has the following date format.

For example: I have a file that contains:

example 1234 Sep/30/2013
example 1234 Jun/2014
example 1234 Oct/03/2013
example 1234 Oct/03/2013
example 1234 Oct/04/2013
example 1234 Oct/01/2013

How can I sort that by the date field?

Thanks in advanced!

Edit: Here is my exact data (noticed I missed one field)

Bones + 9x03 + El Carnicero en el Coche + Sep/30/2013
Haven + 4x04 + Lost and Found + Oct/04/2013
Switched at Birth + 3x01 + Season 3, Episode 1 + Jan/2014
Sleepy Hollow + 1x03 + For the Triumph of Evil + Sep/30/2013
Greys Anatomy + 10x03 + Everybody's Crying Mercy + Oct/03/2013
Falling Skies + 4x01 + Season 4, Episode 1 + Jun/2014
New Girl + 3x03 + Double Date + Oct/01/2013

Here is the command I ran: sort -t'+' -k 4 -M schedule | column -t -s'+'

Switched at Birth                 3x01     Season 3, Episode 1                  Jan/2014
Falling Skies                     4x01     Season 4, Episode 1                  Jun/2014
Bones                             9x03     El Carnicero en el Coche             Sep/30/2013
Sleepy Hollow                     1x03     For the Triumph of Evil              Sep/30/2013
Greys Anatomy                     10x03    Everybody's Crying Mercy             Oct/03/2013
Haven                             4x04     Lost and Found                       Oct/04/2013
New Girl                          3x03     Double Date                          Oct/01/2013

As you can see it still is not sorting correctly.

4

1 回答 1

1

You can use the sort command - more information/examples can be found at this tutorial.

And a link to the man page is here (man sort).

EDIT 2: Since you updated your data, the solution would be: sort -t '+' -k 4.8,4.11 -k 4.1M -k 4.5,4.6 -b my_file.txt

As @sdenham pointed out, the previous answer luckily worked on your example text. However, throwing in some older years breaks the command.

One quick way to solve this using the same command would be to substitute bad dates with a pseudo-day field.

cat example.txt | sed 's:\(.[[:space:]][[:alpha:]]*\)/\([[:digit:]]*\)$:\1/15/\2:g' | sort -t '+' -k 4.8,4.11 -k 4.1M -k 4.5,4.6 -b

Basically, I just threw in a day field of 15 for each row which only had a month/year. Pretty hackish, but it works. I'm sure there's a better way of doing this.

Provided, that is, you're actually using the data format you recently updated with. (Bones + 9x03 + El Carnicero en el Coche + Sep/30/2013)

于 2013-09-30T18:26:39.367 回答