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

Hi, I need to match a particular line from a file and delete it and add a newline for that matched line at the same line number. May I know how I can do this in perl? Can I do that with a single file handle? Thanks, Tom

Replies are listed 'Best First'.
Re: match a line and edit it
by toolic (Bishop) on Mar 17, 2010 at 01:19 UTC
    One way to modify a file in-place is to use Tie::File. The following will replace all lines which have the string 'foo' with the line 'This is now bar':
    use strict; use warnings; use Tie::File; tie my @array, 'Tie::File', 'file.txt' or die $!; for (@array) { if (/foo/) { $_ = 'This is now bar'; } } untie @array;
      Thanks much. That worked.
      May I know, How I can add a new line char with the line I am adding, like
      if (/foo/) { $_ = "This is now bar\n"; }

      I tried the above, but is not adding a new line, I tried to set autochomp => 0 also.
Re: match a line and edit it
by almut (Canon) on Mar 17, 2010 at 01:34 UTC
    $ perl -i.bak -pe 's/^.*foo.*$/bar/' file

    "foo" is the pattern to search for in the line. The whole line will be replaced with "bar".  -p is equivalent to putting while (<>) { ...; print } around the code.  -i.bak does "in-place" editing, creating a backup file with extension .bak.