Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Not sure how to go about this, say i have file1 with
aa aa aa ff ff dd
i need to have an additional number column next to this, but the numbers only increment when the row in column one changes.
aa 1 aa 1 aa 1 ff 2 ff 2 dd 3
numbering is not dependent on letter in column 1, just alters when change. Thanks

Replies are listed 'Best First'.
Re: incrementing a column
by Limbic~Region (Chancellor) on Sep 28, 2004 at 14:13 UTC
    Anonymous Monk,
    Since you were not overly verbose on your requirements, this is the best I can offer:
    #!/usr/bin/perl use strict; use warnings; my $prev_col; my $counter; while ( <DATA> ) { chomp; my ($col, $rest) = $_ =~ /^([^\s]+)(\s.*)$/; if ( ! defined $prev_col || $col ne $prev_col ) { $counter++; $prev_col = $col; } print "$col $counter$rest\n"; } __DATA__ aa one two three aa four five six xy z xy a xy b cc asdfasdf

    Cheers - L~R

Re: incrementing a column
by ikegami (Patriarch) on Sep 28, 2004 at 14:10 UTC
    my $last; my $i = 0; while (<IN>) { chomp; $i++ if (!defined($last) || $_ ne $last); $last = $_; print OUT ("$_ $i\n"); }

    One liner:

    perl -lpe "$i++ if ($_ ne $last); $last = $_; $_.=' '.$i;" inputfile > + outputfile

    (Swap ' for " and vice-versa if you're not using Windows.)

    Update: eek, that's what I get for not testing. Added the missing $last=$_.

      In your one liner ITYM if( $_ ne $last ) { $i++; $last = $_ }.

Re: incrementing a column
by Anonymous Monk on Sep 28, 2004 at 14:28 UTC
    perl -i.bak -pe '$_[$#_]eq$_ or$_[@_]=$_;$_.=" ".@_'
A reply falls below the community's threshold of quality. You may see it by logging in.