Here is my question let's say I have a file
file1.txt with contents:
abc..
def..
ghi..
def..
and second file file2.txt with contents:
xxx..
yyy..
zzz..
Now I want to copy all the line starting with "def" in file1.txt to file2.txt and append after "yyy..." line in file2.txt
xxx...
yyy...
def...
def...
zzz...
I am pretty much new to perl, I've tried writing simple code for this but end up with output only appending at the end of file
#!/usr/local/bin/perl -w
use strict;
use warnings;
use vars qw($filecontent $total);
my $file1 = "file1.txt";
open(FILE1, $file1) || die "couldn't open the file!";
open(FILE2, '>>file2.txt') || die "couldn't open the file!";
while($filecontent = <FILE1>){
if ( $filecontent =~ /def/ ) {
chomp($filecontent);
print FILE2 $filecontent ."\n";
#print FILE2 $filecontent ."\n" if $filecontent =~/yyy/;
}
}
close (FILE1);
close (FILE2);
output of the perl program is
xxx...
yyy...
zzz...
def...
def...
I'd use a temp file.
use strict;
use warnings;
my $file1 = "file1.txt";
my $file2 = "file2.txt";
my $file3 = "file3.txt";
open(FILE1, '<', $file1) or die "couldn't open the file!";
open(FILE2, '<', $file2) or die "couldn't open the file!";
open(FILE3, '>', $file3) or die "couldn't open temp file";
while (<FILE2>) {
print FILE3;
if (/^yyy/) {
last;
}
}
while (<FILE1>) {
if (/^def/) {
print FILE3;
}
}
while (<FILE2>) {
print FILE3;
}
close (FILE1);
close (FILE2);
close (FILE3);
rename($file3, $file2) or die "unable to rename temp file";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With