dan
dan

Reputation: 203

Append a text to the top of a file

I want to add a text on the top of my data.txt file, this code add the text at the end of the file. how I can modify this code to write the text on the top of my data.txt file. thanks in advance for any assistance.

open (MYFILE, '>>data.txt');
print MYFILE "Title\n";
close (MYFILE)

Upvotes: 11

Views: 17485

Answers (6)

chinmoy khaund
chinmoy khaund

Reputation: 119

perl -ni -e 'print "Title\n" $.==1' filename , this print the answer once

Upvotes: -1

Ken
Ken

Reputation: 727

There is a much simpler one-liner to prepend a block of text to every file. Let's say you have a set of files named body1, body2, body3, etc, to which you want to prepend a block of text contained in a file called header:

cat header | perl -0 -i -pe 'BEGIN {$h = <STDIN>}; print $h' body*

Upvotes: 8

tadmc
tadmc

Reputation: 3744

 perl -pi -e 'print "Title\n" if $. == 1' data.text

Upvotes: 13

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15369

Your syntax is slightly off deprecated (thanks, Seth):

open(MYFILE, '>>', "data.txt") or die $!;

You will have to make a full pass through the file and write out the desired data before the existing file contents:

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;
close $in;

unlink($file);
rename("$file.new", $file);

(gratuitously stolen from the Perl FAQ, then modified)

This will process the file line-by-line so that on large files you don't chew up a ton of memory. But, it's not exactly fast.

Hope that helps.

Upvotes: 8

ADW
ADW

Reputation: 4080

See the Perl FAQ Entry on this topic

Upvotes: 2

Seth Robertson
Seth Robertson

Reputation: 31441

Appending to the top is normally called prepending.

open(M,"<","data.txt");
@m = <M>;
close(M);
open(M,">","data.txt");
print M "foo\n";
print M @m;
close(M);

Alternately open data.txt- for writing and then move data.txt- to data.txt after the close, which has the benefit of being atomic so interruptions cannot leave the data.txt file truncated.

Upvotes: 2

Related Questions