Nano HE
Nano HE

Reputation: 9307

How can I concatenate corresponding lines 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 reply.

Attached the completed code which 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"; 
} 

Upvotes: 2

Views: 884

Answers (2)

Salgar
Salgar

Reputation: 7775

I don't think anyone should give a full answer for this.

Just open both files, then loop through both at the same time and write 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

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342333

if Perl is not a must, 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";
}

Upvotes: 3

Related Questions