in reply to Deleting and replacing lines in a file

Here's a naive solution based on the special variable $., which holds the number of lines already read from the last filehandle:
use strict; open INPUT, "<myfile.txt" or die "Could not open input file: $!\n"; open OUTPUT, ">output.txt" or die "Could not open output file: $!\n"; my $count=0; while (<INPUT>) # Loop over lines of file { next unless ($. > 2); # Ignore first two lines s/do my/replacement/ if ($. == 3); print OUTPUT $_; # Print to output file. } close INPUT; close OUTPUT;
When given the input file:
Line 1
Line 2
Line 3 do my
Line 4
it returns the output file:
Line 3 replacement
Line 4
Have fun exploring the wacky world of Perl!

CU
Robartes-

Replies are listed 'Best First'.
Re: Re: Deleting and replacing lines in a file
by Thelonius (Priest) on Feb 14, 2003 at 14:00 UTC
    To add to what robertes says, if you want to put the output of the program back over the input file (as you apparently do), you can use the -i flag of perl:
    #!/usr/bin/perl -w -i.bak use strict; while (<>) # Loop over lines of file { next unless ($. > 2); # Ignore first two lines s/do my/replacement/ if ($. == 3); print $_; }
    Then you can perl edit.pl myinput, which will move the input file to myinput.bak and put the output back in myinput