[mute@geek ~]$ cat cmp
function cmp_date(a,b) {
gsub("-", "", a);
gsub("-", "", b);
if (a > b) return 1;
return 0;
}
{ if (cmp_date($2, a[$1])) a[$1] = $2; }
END { for (i in a) print i, a; }
[mute@geek ~]$ awk -f cmp dates
10 2011-08-01
20 2011-10-01
30 2011-01-20
$ cat jambesh.txt
10 2011-08-01
20 2011-09-02
20 2011-10-01
20 2011-08-02
30 2010-01-20
30 2011-01-20
$ cat script.pl
use warnings;
use strict;
use Time::Local;
@ARGV == 1 or die qq[Usage: perl $0 input-file\n];
my %key;
while ( <> ) {
## Most recent date found and date of current record.
my ($saved_date, $record_date);
next if /\A\s*\z/;
## Split record fields.
chomp;
my ($k, $d) = split;
## If key not processed, save its date and go to next record.
if ( ! exists $key{ $k } ) {
$key{ $k } = $d;
next;
}
## Convert dates to utc and compare them. If date or current record is most
## recent, save it.
{
my ($year,$month,$day) = $key{ $k } =~ m/\A(\d{4})-(\d{2})-(\d{2})\z/;
$saved_date = timelocal( 0, 0, 0, $day, $month - 1, $year - 1900);
}
{
my ($year,$month,$day) = $d =~ m/\A(\d{4})-(\d{2})-(\d{2})\z/;
$record_date = timelocal( 0, 0, 0, $day, $month - 1, $year - 1900);
}
if ( $record_date - $saved_date > 0 ) {
$key{ $k } = $d;
}
}
## Print them.
for ( sort keys %key ) {
printf "%d\t%s\n", $_, $key{ $_ };
}
$ perl script.pl jambesh.txt
10 2011-08-01
20 2011-10-01
30 2011-01-20