sortf rfc dates using bash

若如初见. 提交于 2019-12-06 04:50:22

Similar idea to @meuh, but a single call to perl instead of calling date once for each line:

perl -MTime::Piece -lne '
        push @dates, [Time::Piece->strptime($_, "%a, %e %b %Y %T %z"), $_] 
    } {
        print join "\n", 
              map {$_->[1]} 
              sort {$a->[0] <=> $b->[0]} 
              @dates
' dates.txt
Sat, 13 Sep 2014 12:13:51 -0300
Sun, 19 Jul 2015 14:47:29 -0300
Sat, 1 Aug 2015 01:25:40 +0200
Sat, 1 Aug 2015 01:48:56 +0200

Pass each date through the date command turning them into seconds from the epoch followed by the original string, do the sort, and remove the added seconds:

while read date
do    date --date "$date" +"%s $date"
done |
sort -n -k 1,1 |
sed 's/[^ ]* //'

If your version of sort implements the -M option (sort by month) (and OS X sort does), you can sort the strings on the three relevant fields:

# First, sort on the 4th field numerically (year)
# In the same year, sort on the 3rd field by month
# In the same year and month, sort on the 2nd field numerically (day)
sort -k4,4n -k3,3M -k2,2n dates.txt
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!