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

I am self learning/writting my first .pl. I have a text file i wish to edit using my script. To edit the file i need the first line and the next (blank) line deleted, and the third line replaced. I have the line i need replaced worked out, but how would i delete the first two lines of text in the text file also. Someone please help, i beg of the Monks. Thanks

update (broquaint): title change (was Blind rookie seeking help)

Replies are listed 'Best First'.
Re: Deleting and replacing lines in a file
by robartes (Priest) on Feb 14, 2003 at 10:30 UTC
    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-

      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
Re: Deleting and replacing lines in a file
by Coruscate (Sexton) on Feb 14, 2003 at 10:46 UTC

    It's quite simple really, but if it's your first script, I'm sure it seems very difficult. /me remembers the first scripts he ever wrote and shudders. Something like this might help, assuming that by 'replace the third line' you mean delete it and place something else there:

    #!/usr/bin/perl -Tw use strict; my $file = 'data.txt'; my $fh; open $fh, '<', $file or die "Could not open $file for read: $!"; chomp( my @lines = <$fh> ); close $fh; @lines = ('Replace line 3 with this', @lines[3..$#lines]); open $fh, '>', $file or die "Could not open $file for write: $!"; print $fh join("\n", @lines); close $fh;


    Update: If by 'replace the third line', you meant execute a regex to do a 'search and replace' type of thing, then you can modify my above code to something more along these lines:

    #!/usr/bin/perl -Tw use strict; my $file = 'data.txt'; my $fh; open $fh, '<', $file or die "Could not open $file for read: $!"; chomp( my @lines = <$fh> ); close $fh; $lines[2] =~ s/foo/bar/g; @lines = (@lines[2..$#lines]); open $fh, '>', $file or die "Could not open $file for write: $!"; print $fh join("\n", @lines); close $fh;


    If the above content is missing any vital points or you feel that any of the information is misleading, incorrect or irrelevant, please feel free to downvote the post. At the same time, reply to this node or /msg me to tell me what is wrong with the post, so that I may update the node to the best of my ability. If you do not inform me as to why the post deserved a downvote, your vote does not have any significance and will be disregarded.

Re: Deleting and replacing lines in a file
by Corion (Patriarch) on Feb 14, 2003 at 12:35 UTC

    There is a really nice and simple-to-use module called Tie::File, which allows you to access a file as if it were a perl array :

    use strict; use Tie::File; my @file; my $filename = 'test.txt'; tie @file, 'Tie::File', $filename or die "Couldn't open '$filename' : $!\n"; die "The second line in '$filename' is not blank !\n" unless $file[1] eq ''; # Remove first line : shift @file; # Remove second line : shift @file; # Replace first (former third) line : $file[0] = "New text";
    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
Re: Deleting and replacing lines in a file
by steves (Curate) on Feb 14, 2003 at 10:39 UTC

    I assume you've already set up your script to read the file and write the changed results somewhere else. Something like this if you were reading from standard input and writing to standard output:

    while (<>) { # edit line if needed. print $_; }
    If that's the case and you always want to do something to lines 1, 2, and 3, you could just use a counter:
    my $line = 0; while (<>) { ++$line; next if ($line < 3); # skip first two lines s/XXXX/YYYY if ($line == 3); # change third line print $_; }
Re: Deleting and replacing lines in a file
by jdporter (Paladin) on Feb 15, 2003 at 03:13 UTC
    In addition to the fine advice given so far, I'd like to add some other WTDI:
    #!/bin/perl -ni.bak print $. < 3 ? () : $. > 3 ? $_ : "new third\n";
    #!/bin/perl -ni.bak print } BEGIN { scalar <>; scalar <>; scalar <>; print "This text replaces the third line.\n"; } {
    Of course, it doesn't work right if you specify more than one file on the command line, but hey...

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.