Reputation: 475
I am reading from two files. I'm trying to insert a line from file2 to file1 whenever column 1 contents matches.
##FILE1
1 wr 5769 78670002 fqefq
3 wr 5769 78650003 hfhhg
5 wr 5769 88990001 dfdsv
##FILE2
1 Step1
3 Step3
5 Step5
Desired Output:
1 wr 5769 78670002 fqefq
Step1
3 wr 5769 78650003 hfhhg
Step3
5 wr 5769 88990001 dfdsv
Step5
Code tried:
my $rk="rk.log";
open(my $tt, "<$rk" ) or die "Could not open file $trk: $!";
while (<$tt>) {
if ($_ =~ /^(\d+)\s+wr\s+5769\s+(\w+)\s+\.*/gm) {
open(p1,"<$temp1") or die "Could not open file $temp1: $!";
while (my $newl = <p1>) {
my @fs1 = split " ", $newl;
if ($fs1[0] eq $1){
print "@fs1\n";
print "step $2\n";
} else {
print "@fs1\n";
}
}
}
}
close p1;
close $tt;
Above code doesn't giving the desired output. Can anyone suggest me better way to do it?
Update ##FILE2
2 Step1
4 Step3
6 Step5
Upvotes: 2
Views: 132
Reputation: 2589
This is works for me:
use Tie::File;
my $fle1 = $ARGV[0]; my $fle2 = $ARGV[1];
open(FL2, $fle2) || die "Couldn't read file $fle2\: $!\n";
my $flecnt2 = do { local $/; <FL2>; };
close(FL2);
my @array;
tie @array, 'Tie::File', $fle1 || die "Error: Couldn't read and write \"$fle1\" file: $!";
my $str = join "\n", @array;
$str=~s#^([^\s]+)\s(.+)$# my $fulcnt=$&;
if($flecnt2=~m/^$1\s+(.+)$/m)
{
$fulcnt .= "\n$&";
}
($fulcnt);
#egm;
@array = split/\n/, $str;
untie @array;
Upvotes: 0
Reputation: 171
I believe the simplest method would be to import the two files into separate strings, then create a loop which:
This way you will sequentially order all of your matches from the two files into a string that you can export as a file.
Upvotes: 0
Reputation: 69314
Hopefully, a bit of pseudocode will be enough to get you on the right track.
Upvotes: 3