How do I add lines to the top and bottom of a file in Perl?

24,578

Solution 1

From perlfaq5's answer to How do I change, delete, or insert a line in a file, or append to the beginning of a file?


How do I change, delete, or insert a line in a file, or append to the beginning of a file?

(contributed by brian d foy)

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

Use Tie::File which gives you access to the lines of a disk file via a Perl array. It comes with standard distribution.

Example from documentation:
use Tie::File;

tie @array, 'Tie::File', filename or die ...;
$array[13] = 'blah';     # line 13 of the file is now 'blah'
print $array[42];        # display line 42 of the file

$n_recs = @array;        # how many records are in the file?
$#array -= 2;            # chop two records off the end

for (@array) {
    s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
}

# These are just like regular push, pop, unshift, shift, and splice
# Except that they modify the file in the way you would expect
push @array, new recs...;
my $r1 = pop @array;
unshift @array, new recs...;
my $r2 = shift @array;
@old_recs = splice @array, 3, 7, new recs...;

untie @array;            # all finished

Solution 3

Three answers have been given that perpetuate the very bad practice of:

open(FILE,"<file") or die "cannot open";

Not only that, the code is broken since you are not opening the file for writing but for reading.

When an open fails, you can tell the user why it failed. Please get in the habit of including $! in the error message. Also, use the three argument form of open to separate the mode from the name:

my $path="file";
open my($fh), '>', $path or die "$path: $!";

(This does not answer your question, but I'm making it an answer rather than a comment for added emphasis and so that I can review it as it is a rather lengthy spewing forth.)

Solution 4

Perl can't insert at the beginning of a file because few operating systems allow that. You need a rewrite operation of the type you have here.

One possible problem you may have with that code is with truly large files that can't fit in your address space.

By reading the entire file in then writing it out, you may run into memory problems. What I would have done would be to:

  • rename the current file
  • re-create it with the stuff you want inserted at the start,
  • copy the renamed file in large chunks (not necessarily lines) to the end of the new file,
  • add the new bit at the end.

This will be fast and memory-efficient.

Of course, if your files are small enough to fit in memory, stick with what you have. It's good enough.

Update:

Enough people seem to be under the misapprehension that I'm advocating a shell script that I thought I'd set it straight. You can do all the things above from within native Perl.

But you may want to consider if it's necessary to use Perl. A shell command like:

( echo '9   431';cat /usr/old;echo '(3,((((1,4),(7,6)),(2,8)),5),9)' ) >/usr/new

will do the trick just as well (and probably just as fast).

Of course, if you need Perl, then just ignore this update as the ramblings of an old man :-)

Share:
24,578
shubster
Author by

shubster

Updated on August 17, 2020

Comments

  • shubster
    shubster over 3 years

    I want to add a line to top and bottom of the file. I can do it following way.

    open (DATA, "</usr/old") || die "cant open old\n"; #file to which line has to be added
    
    my @body=<DATA>;
    close(DATA);
    
    open (FILE, ">/usr/new") || die "cant open new\n"; #file after stuff has been added
    
    print FILE "9   431";
    
    print FILE "\n";
    
    my $body=@body;
    
    for (my $i=0; $i<$body;$i++){
    
        print FILE "$body[$i]";#not using for loop leads to addition of spaces in new file
    }
    
    print FILE "(3,((((1,4),(7,6)),(2,8)),5),9)";
    

    Since I running for a large set of file this process will be time consuming. Does Perl has any specific functionality which used to add lines at top and bottom of a file?

  • paxdiablo
    paxdiablo almost 15 years
    I didn't actually advocate a shell script, you can do all the things I mentioned with native Perl. But, of course, if Perl isn't a pre-req, you could do: ( echo "start line" ; cat file ; echo "end line" ) > file2 ; mv file2 file
  • zakovyrya
    zakovyrya almost 15 years
    As one man once said, "If we all worked on the assumption that what is accepted as true were really true, there would be little hope of advance". See my answer below: stackoverflow.com/questions/1230654/…
  • paxdiablo
    paxdiablo almost 15 years
    @zakovyrya, you should look at the source code beneath Tie::File to see what it's doing :-) Then let me know how that's better from a performance POV.
  • zakovyrya
    zakovyrya almost 15 years
    @Pax, sometimes it's ok to trade performance for programmer's convenience. In fact, take a look at the whole history of so called computer science.