How can I sort a text file which contains rfc dates?
Eg.:
Sat, 1 Aug 2015 01:48:56 +0200 Sat, 1 Aug 2015 01:25:40 +0200 Sun, 19 Jul 2015 14:47:29 -0300 Sat, 13 Sep 2014 12:13:51 -0300
Thanks!
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/[^ ]* //'
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
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