Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append a text on the top of the file

Tags:

shell

perl

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)
like image 828
dan Avatar asked May 26 '11 15:05

dan


People also ask

How do I append the contents of a file?

The >> operator redirects output to a file. If the mentioned file doesn't exist the file is created and then the text is appended to the file. Alternatively, we can use printf command to append text into a file. We can also use the cat command to append the content of one file to another file.

Which command is used to append in a file?

You can use the cat command to append data or text to a file. The cat command can also append binary data. The main purpose of the cat command is to display data on screen (stdout) or concatenate files under Linux or Unix like operating systems.


2 Answers

 perl -pi -e 'print "Title\n" if $. == 1' data.text
like image 76
tadmc Avatar answered Oct 14 '22 06:10

tadmc


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.

like image 21
Justin ᚅᚔᚈᚄᚒᚔ Avatar answered Oct 14 '22 07:10

Justin ᚅᚔᚈᚄᚒᚔ