Datafile conversion with AWK !

Larry Wall lwall at jpl-devvax.JPL.NASA.GOV
Fri Dec 15 09:56:35 AEST 1989


In article <539 at csoftec.csf.com> root at csoftec.csf.com (Cliff Manis (cmanis at csoftec)) writes:
: I am needing help with data conversion, and would appreciate help 
: in AWK or SED and/or awk & sed.   Or whatever....

Here is, of course, the answer in "whatever":        :-)

#!/usr/bin/perl

@key = ('','','');
while (<>) {
    ($key,$addr,$rest,$sub) = /^([^|]*\|[^|]*\|[^|]*)\|([^|]*)\|(.*(\d))/;
    &printone if $key ne $lastkey;
    $addr[$sub-1] = $addr;
}
&printone;

sub printone {
    print join('|',$lastkey, at addr,$lastrest),"\n" if $lastkey ne '';
    $lastkey = $key;
    $lastrest = $rest;
    @addr = ('','','','');
}

I think you should find this fairly readable.

If you're uncomfortable with the hairy regular expression, here's one
that uses split instead:

#!/usr/bin/perl

@key = ('','','');
while (<>) {
    (@key[0..2],$addr, at remainder) = split(/[|]/,$_,14);
    $sub = pop(@remainder);
    $key = join('|', at key);
    &printone if $key ne $lastkey;
    $addr[$sub-1] = $addr;
}
&printone;

sub printone {
    print join('|',$lastkey, at addr, at lastremainder,"1\n") if $lastkey ne '';
    $lastkey = $key;
    @lastremainder = @remainder;
    @addr = ('','','','');
}

Larry Wall
lwall at jpl-devvax.jpl.nasa.gov



More information about the Comp.unix.questions mailing list