Andy897
Andy897

Reputation: 7133

Perl script to merge multiple files line by line

Can anyone please help me with writing a Perl script which can take as input 5 text files and create a new text file with merging each row of all 5 files. Should this be done by opening 5 read streams at a time or like java some random file reader is available in Perl ?

Thank You!

Upvotes: 0

Views: 9543

Answers (3)

Borodin
Borodin

Reputation: 126722

This program expects a list of files on the command line (or, on Unix systems, a wildcard file spec). It creates an array of filehandles @fh for these files and then reads from each of them in turn, printing the merged data to STDOUT

use strict;
use warnings;

my @fh;
for (@ARGV) {
  open my $fh, '<', $_ or die "Unable to open '$_' for reading: $!";
  push @fh, $fh;
}

while (grep { not eof } @fh) {
  for my $fh (@fh) {
    if (defined(my $line = <$fh>)) {
      chomp $line;
      print "$line\n";
    }
  }
}

Upvotes: 5

dan1111
dan1111

Reputation: 6566

Here is a Perl script that will work on an arbitrary number of files:

use strict;
use warnings;

my @files = ('a.txt','b.txt');
my @fh;

#create an array of open filehandles.
@fh = map { open my $f, $_ or die "Cant open $_:$!"; $f } @files;

open my $out_file, ">merged.txt" or die "can't open out_file: $!";

my $output;
do
{
    $output = '';

    foreach (@fh)
    {
        my $line = <$_>;
        if (defined $line)
        {
            #Special case: might not be a newline at the end of the file
            #add a newline if none is found.
            $line .= "\n" if ($line !~ /\n$/);
            $output .= $line;
        }
    }

    print {$out_file} $output;
}
while ($output ne '');

a.txt:

foo1
foo2
foo3
foo4
foo5

b.txt:

bar1
bar2
bar3

merged.txt:

foo1
bar1
foo2
bar2
foo3
bar3
foo4
foo5

Upvotes: 7

Guru
Guru

Reputation: 16974

If a non-perl solution is ok with you, you can try this:

paste -d"\n\n\n\n\n" f1 f2 f3 f4 f5

where f1,f2..are your text files.

Upvotes: 5

Related Questions