mee mee mee mee - 5 months ago 8
Perl Question

how to append new rows at the top of existing .txt file?

Hi I like to append new rows of data in existing

file. I use below script. It did append new rows but it appended at the bottom. I would like to append my new rows at the top of existing row. How can i do that?

my $filename = 'file.txt';
open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!";
print $fh "-----------\n";
close $fh;


You'd need to rewrite the file. The >> opens the file so that it is appended to, added to the back of it.

For small enough files

use warnings;
use strict;

my $filename = 'file_to_prepend_to.txt';
my @lines_to_prepend = ("line 1", "line 2");

# slurp the whole file into a variable
my $filecont = do {
    local $/;
    open my $fh, '<', $filename or die "Can't open $filename: $!";

# open the file for writing, to overwrite
open my $fh, '>', $filename or die "Can't open $filename: $!";

# write new contents first
for my $line (@lines_to_prepend) {
    print $fh "$line\n";

# dump the old contents now
print $fh $filecont;
close $fh;

The local $/ sets the input record separator to an undef so that the whole file is read in one read by <>, into a scalar. Once that do block is done the filehandle is closed. Note the \n in the print, adding a newline -- if your lines-to-prepepnd already have it remove that.

For very large files you'd want to read line by line and write them out to a new file (to which you first wrote lines to prepend), then move that new file to overwrite the original one.