Extracting Max date for multiple same key

Can any one help me to sort and extract the max date row from multiple same key ?

example of input file
kEY DATE(YYY-MM-DD)

10   2011-08-01
20   2011-09-02
20   2011-10-01
20   2011-08-02
30   2010-01-20
30   2011-01-20

Out put :

10 2011-08-01co
20 2011-10-01
30 2011-01-20

The out put is extracted based on max date from right column if the left column have same keys key (20/30).

If the left side has no duplicate key then it should pick that record (e.g with key 10)

Thanks
JM

Solution using an awk script.

[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

Hi jambesh,

Using 'Perl':

$ 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

Regards,
Birei

The order of the keys ($1) will not be preserved/guaranteed.

awk 'END {
  for (K in k) print K, k[K]
  }
{ $2 > k[$1] && k[$1] = $2 }
  ' infile

If your sort supports the "-s" stable option:

sort -k1,1 -k2,2r infile |sort -k1,1 -su

Another Perl solution:

$
$
$ cat f26
10   2011-08-01
20   2011-09-02
20   2011-10-01
20   2011-08-02
30   2010-01-20
30   2011-01-20
$
$
$
$ perl -lane 'if ($F[0] eq $key and $F[1] gt $val) {$val = $F[1]}
              elsif ($F[0] != $key) {print "$key   $val" if defined $key; ($key, $val) = @F}
              END {print "$key   $val"}
             ' f26
10   2011-08-01
20   2011-10-01
30   2011-01-20
$
$
$

tyler_durden