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

Great Ones, I have a file with lines that look like this:
N7 some text N8 some more text N9 more text N10 and more text N90 many lines of text alot of text N101 too much text text text
I need help with perl to renumber the lines above to look like this:
N1 some text N2 some more text N3 more text N4 and more text N5 many lines of text N6 alot of text N7 too much text N8 text text
I have alot of these files with 100's of lines in each one. This seems like it should be simple (for someone besides me!) Thanks for in advance for any offerings on this!

Replies are listed 'Best First'.
Re: Line Renumbering
by FoxtrotUniform (Prior) on Aug 29, 2002 at 16:32 UTC

    Note: untested.

    $ perl -i.bak -lpe "s/^(N\d+ )?/$./" *.input
    • The -i.bak switch says "edit the input files in place, making backup files for each with a .bak extension".
    • The -l switch says "do automatic line-end processing".
    • The -p switch says "iterate over each line". Well, it does a bit more than that; see perldoc:perlrun for more.
    • The $. special variable holds the input line number (like NR in awk).

    --
    F o x t r o t U n i f o r m
    Found a typo in this node? /msg me
    The hell with paco, vote for Erudil!

      Unfortunately, when using <> (as -p does), $. is not reset after the close of each file. However, there is an example in the perlfunc:eof documentation of how to get around this (basically, you just have to do an explicit test of eof, then close the filehandle when it is found). The example is easily modified to fit this problem:
      #!/usr/bin/perl -i.bak while (<>) { s/^(N\d+ )?/N$. /; } continue { print; close ARGV if eof; }

      -- Mike

      --
      just,my${.02}

      There's only a nasty caveat about $. on ARGV: it is not reset for each file, so it seems neccessary to "recode" the behaviour of <> in order to make this work as intended.

      --
      http://fruiture.de
Re: Line Renumbering
by cLive ;-) (Prior) on Aug 29, 2002 at 17:52 UTC
    Something like this?
    #!/usr/bin/perl -w use strict; open(OLDF,"file.txt") || die $!; open(NEWF,">newfile.txt") || die $!; my $line=1; while (<OLDF>) { s/^\s*(N\d+)?\s*/N$line /; print NEWF; $line++; } close(OLDF); close(NEWF);

    cLive ;-)

    --
    seek(JOB,$$LA,0);

      How about something simple like: #!perl $myfile="c:/myfile.txt"; open MYFILE, $myfile or die "Cannot open $myfile for read :$!"; while (<MYFILE>) { print "N1 $. $_"; } while (<MYFILE>) { print "N $. $_"; }
        OOPS My Bad- the above post shoulda been: #!perl $myfile="c:/myfile.txt"; open MYFILE, $myfile or die "Cannot open $myfile for read :$!"; while (<MYFILE>) { print "N1 $. $_"; }