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.


In reply to Re: Deleting and replacing lines in a file by Coruscate
in thread Deleting and replacing lines in a file by Dobro

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.