How do I replace lines in the middle of a file with Perl?

59,990

Solution 1

I think this is the FAQ answer that I've reposted to Stackoverflow the most. The perlfaq5 has the answer to How do I change, delete, or insert a line in a file, or append to the beginning of a file?.

Forget about the append mode stuff. That's just going to make your life harder.


The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn't provide random access to lines (especially since the record input separator, $/, is mutable), although modules such as Tie::File can fake it.

A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

while( <$in> )
    {
    print $out $_;
    }

close $out;

Within that basic form, add the parts that you need to insert, change, or delete lines.

To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC

while( <$in> )
    {
    print $out $_;
    }

close $out;

To change existing lines, insert the code to modify the lines inside the while loop. In this case, the code finds all lowercased versions of "perl" and uppercases them. The happens for every line, so be sure that you're supposed to do that on every line!

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n";

while( <$in> )
    {
    s/\b(perl)\b/Perl/g;
    print $out $_;
    }

close $out;

To change only a particular line, the input line number, $., is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those:

while( <$in> )   # print the lines before the change
    {
    print $out $_;
    last if $. == 4; # line number before change
    }

my $line = <$in>;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;

while( <$in> )   # print the rest of the lines
    {
    print $out $_;
    }

To skip lines, use the looping controls. The next in this example skips comment lines, and the last stops all processing once it encounters either __END__ or __DATA__.

while( <$in> )
    {
    next if /^\s+#/;             # skip comment lines
    last if /^__(END|DATA)__$/;  # stop at end of code marker
    print $out $_;
    }

Do the same sort of thing to delete a particular line by using next to skip the lines you don't want to show up in the output. This example skips every fifth line:

while( <$in> )
    {
    next unless $. % 5;
    print $out $_;
    }

If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!):

open my $in,  '<',  $file      or die "Can't read old file: $!"
open my $out, '>', "$file.new" or die "Can't write new file: $!";

my @lines = do { local $/; <$in> }; # slurp!

    # do your magic here

print $out @lines;

Modules such as File::Slurp and Tie::File can help with that too. If you can, however, avoid reading the entire file at once. Perl won't give that memory back to the operating system until the process finishes.

You can also use Perl one-liners to modify a file in-place. The following changes all 'Fred' to 'Barney' in inFile.txt, overwriting the file with the new contents. With the -p switch, Perl wraps a while loop around the code you specify with -e, and -i turns on in-place editing. The current line is in $_. With -p, Perl automatically prints the value of $_ at the end of the loop. See perlrun for more details.

perl -pi -e 's/Fred/Barney/' inFile.txt

To make a backup of inFile.txt, give -i a file extension to add:

perl -pi.bak -e 's/Fred/Barney/' inFile.txt

To change only the fifth line, you can add a test checking $., the input line number, then only perform the operation when the test passes:

perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt

To add lines before a certain line, you can add a line (or lines!) before Perl prints $_:

perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt

You can even add a line to the beginning of a file, since the current line prints at the end of the loop:

perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt

To insert a line after one already in the file, use the -n switch. It's just like -p except that it doesn't print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add.

perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt

To delete lines, only print the ones that you want.

perl -ni -e 'print unless /d/' inFile.txt

    ... or ...

perl -pi -e 'next unless /d/' inFile.txt

Solution 2

You can do this with Tie::File. (Be aware that it will have to rewrite the entire file in order to replace the initial lines, but Tie::File will hide the details from you.)

Solution 3

A good Perl idiom is to read and write the standard input and output. You can pipe and redirect as necessary. Through the operator <> (a wrap to readline), Perl will open the files you pass as argument on the command line.

To answer your question, a few lines of code (as clean as possible) :

#!/usr/bin/env perl
use strict; use warnings;

while (<>) {
  if ($. == 2) {
    print "new data", "\n";
    next;
  }
  if ($. == 3) {
    print "very new data", "\n";
    next;
  }
  print;
}

print "more data", "\n"; 

Then call it this way : perl yourscript.pl inputfile > outputfile

If you want to open the files yourself (here we simply skip the unwanted lines) :

my open $in_fh, '<', $inputfile
  or die "Can't open file $inputfile: $!";

my open $out_fh, '>', $outputfile
  or die "Can't open file $output: $!";

while (my $line = <$in_fh>) {
  next if ( $. == 2 or $. == 3 or $. == 4 );
  print $out_fh $line;
}
print $out_fh "...whatever\n";
Share:
59,990

Related videos on Youtube

kkchaitu
Author by

kkchaitu

I have 12+ years of IT experience in System Analysis, Design and Development of applications in JavaScript, CSS, HTML and HTML technologies, which are built highly scalable and fault tolerant.

Updated on July 09, 2022

Comments

  • kkchaitu
    kkchaitu almost 2 years

    I am opening the file in append mode. I need to replace lines 2,3, and 4 in the file, and later I need to add the new data at the end of the file.

    • huynhjl
      huynhjl about 14 years
      It does not look like opening the file in append mode is consistent with replacing line 2,3,4 that have already been written.
    • kkchaitu
      kkchaitu about 14 years
      How I can dump data from one file to another with the desired data and add the new data at the end
    • Larry K
      Larry K about 14 years
      You need to open two files, one that you read from and one that you write to. Then loop through the first, and add appropriate data from it to the second file.
    • jgmao
      jgmao almost 8 years
      I have the same question. But, note that in my case the file has to be changed in-line. Which means, it is neither possible to open a new file to write as the FAQ's method, nor feasible to run 'perl -pi' in bash. Don't think the answer is helpful.
  • Larry K
    Larry K about 14 years
    @hobbs, See the perl doc, perldoc.perl.org/perlopentut.html It says mode +>> (read and append) "...will allow you to read at any point in the file, but all writes will always go to the end." So be careful, one system's implementation doesn't mean it's correct.
  • Adam Millerchip
    Adam Millerchip about 8 years
    The link to the FAQ is broken, correct link: learn.perl.org/faq/…. I tried to edit it but the editor wouldn't let me save, throwing up a message about code indentation.