[wellylug] bash / sed / awk tricky question

Grant McLean grant at mclean.net.nz
Fri Feb 4 16:47:50 NZDT 2005


On Fri, 2005-02-04 at 14:13 +1300, Glen Ogilvie wrote:
> Hi,
> 
> I have a quite tricky scripting question...
> 
> ... I am trying to write a shell / sed / awk script

I have a rule of thumb that if something is likely to take more than 5
lines of code then I start writing it in Perl rather than shell.

Here's a Perl solution:


#!/usr/bin/perl -w

use strict;

my %p;

while(<>) {
  add_package($_);
}

foreach my $k (sort keys %p) {
  print $p{$k}->[1];
}

exit;

sub add_package {
  my($name) = @_;

  if($name =~ /^(.*?)-(\d.*)$/) {
    my $pkg = $1;
    my $version = join '.',
                    map { /^\d+$/ ? sprintf('%09u', $_) : $_ } 
                    split /\./, $2;
    $p{$pkg} ||= [ $version, $name ];
    if($version gt $p{$pkg}->[0]) {
      $p{$pkg} = [ $version, $name ];
    }
  }
}


The most complicated part is the join ... map ... split statement that
converts something like this:

  2.3.25-1thac.i586.rpm

to this:

  000000002.000000003.000000025.1thac.i586.rpm

which can then be safely ordered with a string 'gt' comparison operator.

Of course it would all go horribly pear shaped if that '1thac' bit
cycled through '9thac' to '10thac' :-(

Cheers
Grant




More information about the wellylug mailing list