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.
|