9

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)
dreftymac
  • 31,404
  • 26
  • 119
  • 182
dan
  • 185
  • 1
  • 5
  • 11
  • http://stackoverflow.com/questions/2322140/how-do-i-change-delete-or-insert-a-line-in-a-file-or-append-to-the-beginning-o – daxim May 27 '11 at 09:34

6 Answers6

11
 perl -pi -e 'print "Title\n" if $. == 1' data.text
tadmc
  • 3,714
  • 16
  • 14
  • 3
    Excellent one-liner, but it should be noted that this still loops through the file line-by-line and prints each one back to the original file. See http://oreilly.com/pub/h/73 for a great write-up on this use case. – Justin ᚅᚔᚈᚄᚒᚔ May 27 '11 at 15:04
  • how to add one line to each file of file globs? like *.txt – fchen Apr 08 '18 at 17:48
8

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*
Ken
  • 717
  • 7
  • 9
8

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.

Justin ᚅᚔᚈᚄᚒᚔ
  • 15,081
  • 7
  • 52
  • 64
2

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.

Seth Robertson
  • 30,608
  • 7
  • 64
  • 57
2

See the Perl FAQ Entry on this topic

ADW
  • 4,030
  • 17
  • 13
-1

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