Hi, Perl is new to me. I am trying to insert a line to a file.
Example: I have a file (trial.txt), content:
ZZZZ
AAA
DDDD
I am trying to insert CCC below AAA.
MY perl command:
open (FILE,"+>>C:\\Documents and Settings\\trial.txt\n")|| die "can't open file";
while(<FILE>)
{
if(/AAA/)
{
print FILE "CCC\n";
}
}#end while
close(FILE);
The output I get:
ZZZZ
AAA
DDDD
ZZZZ
AAA
CCC
Where else what I need is:
ZZZZ
AAA
CCC
DDDD
It appends the whole file again and replaces the next line after AAA with CCC, where else what I need is to insert CCC in the existing file below AAA. Thanks to advise.
Im afraid you cannot simply insert lines into a file in this manner - you have to either read the whole file into memory and write back the new file, or you have to write the output to a temporary file.
Here is an example of the former...
#!/usr/bin/perl
open(FILE,"foo.txt") || die "can't open file for read\n";
my @lines=<FILE>;
close(FILE);
open(FILE,">foo.txt")|| die "can't open file for write\n";
foreach $line (@lines) {
if($line =~ /AAA/) {
print FILE "CCC\n";
} else {
print FILE $line;
}
}#end foreach
close(FILE);
Thanks citaylor :).. tried applying your example, but it still replaces the AAA with CCC, instead of adding the CCC below AAA. Meanwhile, I am trying to google for any tips on this, no luck so far..
#!/usr/bin/perl
open(FILE,"foo.txt") || die "can't open file for read\n";
my @lines=<FILE>;
close(FILE);
open(FILE,">foo.txt")|| die "can't open file for write\n";
foreach $line (@lines) {
print FILE "CCC\n" if($line =~ /AAA/);
print FILE $line;
}#end foreach
close(FILE);