I have some 30,000 files of 5MB each. I wanted to append some few lines on the top
of every file. I had done that using bash script. I wanted to learn a way to do it using perl.
Asked
Active
Viewed 350 times
0

aravind ramesh
- 307
- 2
- 15
-
How do you find these files? Are they in a single directory, or littered throughout a filesystem? – Cliff Mar 19 '14 at 05:01
-
In a single directory. I have list of the names in a file named `list` – aravind ramesh Mar 19 '14 at 05:03
-
1From SO: [`append a text on the top of the file`](http://stackoverflow.com/questions/6141088/append-a-text-on-the-top-of-the-file) from May 26 '11. Or [`How do I add lines to the top and bottom of a file in Perl?`](http://stackoverflow.com/questions/1230654/how-do-i-add-lines-to-the-top-and-bottom-of-a-file-in-perl) from Aug 5 '09. From Perldoc: [`How do I change, delete, or insert a line in a file, or append to the beginning of a file?`](http://learn.perl.org/faq/perlfaq5.html#How-do-I-change-delete-or-insert-a-line-in-a-file-or-append-to-the-beginning-of-a-file-) – Miller Mar 19 '14 at 05:04
1 Answers
0
This is an example of how to do it. I'd probably put in a fgw more error checks, like one on the rename, and I would probably want make sure I can read and write to the files and directory.
#!/usr/bin/env perl
use strict
use File::Glob ':glob';
my @files = bsd_glob('/some/path/to/files*');
for my $file (@files)
{
open my $in, '<', $file
or die "Can't open file: $!";
open my $out, '>', "$file.new"
or die "Can't write new file: $!";
while(<$in>)
{
print $out $_;
}
close $in;
close $out;
rename "$file.new", $file;
}

Cliff
- 1,621
- 1
- 13
- 22
-
Thanks for the answer. I thought we will have to use '>+' file handles ops like these. When to use them ? any tutorial will help. – aravind ramesh Mar 19 '14 at 05:10
-
2As far as I recall, when using the >+ open type, you have to be very careful with bytes you read and write. You will overwrite existing data if you are not careful. It's for flipping bits and bytes, not for prepending data. You can change "cat" to "dog" for example, but you would start overwriting data if you changed "cat" to "fish". – Cliff Mar 19 '14 at 05:15
-
See http://perldoc.perl.org/functions/open.html: "You can't usually use either read-write mode for updating textfiles, since they have variable-length records." – Cliff Mar 19 '14 at 05:15