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


I don't think anyone needs to give a complete answer for this.

Just open both files, then run both at the same time and write them out to a new file.



If you don't know how to read and write files in perl, here is a tutorial:

http://perl.about.com/od/perltutorials/a/readwritefiles.htm

+1


a source







All Articles