How can I concatenate matching strings in two files in Perl?
file1.txt
hello
tom
well
file2.txt
world
jerry
done
How to merge file1.txt with file2.txt; then create a new file - file3.txt
hello world
tom jerry
well done
thank you for reading and answering.
See attached code which is based on the answer.
#!/usr/bin/perl
use strict;
use warnings;
open(F1,"<","1.txt") or die "Cannot open file1:$!\n";
open(F2,"<","2.txt") or die "Cannot open file2:$!\n";
open (MYFILE, '>>3.txt');
while(<F1>){
chomp;
chomp(my $f2=<F2>);
print MYFILE $_ . $f2 ."\n";
}
+2
a source to share
2 answers
if Perl is optional, you can just use paste
on * nix. If you are on Windows you can also use paste
. Just download from GNU win32
$ paste file1 file2
else, in Perl
open(F1,"<","file1") or die "Cannot open file1:$!\n";
open(F2,"<","file2") or die "Cannot open file2:$!\n";
while(<F1>){
chomp;
chomp($f2=<F2>);
print $_ . $f2 ."\n";
}
+3
a source to share