Linux - 按日期字段排序文件

时间:2013-09-30 18:21:30

标签: linux file date converter

我正在尝试按日期字段对文件进行排序。我之前已经意识到这已经完成,但是,我找不到具有以下日期格式的示例。

例如: 我有一个包含以下内容的文件:

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

如何按日期字段对其进行排序?

先谢谢!

编辑: 这是我的确切数据(注意到我错过了一个字段)

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

这是我运行的命令: sort -t'+' - k 4 -M schedule |列-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

正如您所看到的,它仍然没有正确排序。

1 个答案:

答案 0 :(得分:1)

您可以使用sort命令 - 更多信息/示例可以是found at this tutorial

And a link to the man page is hereman sort)。

编辑2:由于您更新了数据,解决方案将是:sort -t '+' -k 4.8,4.11 -k 4.1M -k 4.5,4.6 -b my_file.txt

正如@sdenham指出的那样,上一个答案很幸运地适用于你的示例文本。然而,在一些年纪较大的时间里投掷会破坏命令。

使用相同命令解决此问题的一种快速方法是使用伪日字段替换错误日期。

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

基本上,我只是为day字段投放15字段,每行只有一个月/年。非常hackish,但它的工作原理。我确信有更好的方法可以做到这一点。

提供,即您实际上使用的是最近更新过的数据格式。 (Bones + 9x03 + El Carnicero en el Coche + Sep/30/2013