开发者

How can I concatenate corresponding lines in two files in Perl?

开发者 https://www.devze.com 2022-12-26 18:36 出处:网络
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

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"; 
} 


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";
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消