i have multiple text files.I have written code to input 2 files through shell and merge them.But how do i merge multiple files.Is system command useful in this purpose.
my @a = read_file($file1)
or die "couldn't read $file1 - $!";
my @b = read_file($file2)
or die "couldn't read $file2 - $!";
my $combined = {}; # hashref
my $i=0;
foreach (@a) {
chomp;
$combined->{$i}{b} = '' unless defined $combined->{$i}{b};
$combined->{$i++}{a} = $_;
}
$i=0;
foreach (@b) {
chomp;
$combined->{$i}{a} = '' unless defined $combined->{$i}{a};
$combined->{$i++}{b} = $_;
}
foreach my $i (sort {$a<=>$b} keys %$combined) {
print $combined->{$i}{a}, ("\t" x 2), $combined->{$i}{b}, "\n";
}
As I understand, you can read one line at the same time for both files and print each line separated with tabs, like:
use warnings;
use strict;
die unless @ARGV == 2;
open my $fha, q|<|, $ARGV[0] or die;
open my $fhb, q|<|, $ARGV[1] or die;
while ( my $a = <$fha>, my $b = <$fhb> ) {
chomp( $a, $b );
printf qq|%s\t\t%s\n|, $a, $b;
}
This script won't work if files have different number of lines. You will need another approach for that situation.
You can do it simply in shell: cat file1.txt file2.txt file3.txt > selected.txt
Or in Perl:
use strict;
@ARGV = ('file1.txt', 'file2.txt', 'file3.txt');
open MULTI, '>', 'selected.txt'
or die $!;
while (<>) {
print MULTI;
}
How about:
#!/usr/bin/perl
use strict;
use warnings;
my @files = qw(file1 file2 file3 file4);
my %content;
my $max_rec = 0;
foreach (@files) {
open my $fh, '<', $_ or die $!;
@{$content{$_}} = <$fh>;
chomp @{$content{$_}};
close $fh;
$max_rec = @{$content{$_}} if scalar(@{$content{$_}}) > $max_rec;
}
open my $fh, '>', 'outfile' or die $!;
for my $i (0 .. $max_rec) {
my $out = '';
foreach (@files) {
$out .= defined($content{$_}[$i]) ? $content{$_}[$i] : '';
$out .= "\t\t" unless $_ eq $files[-1];
}
print $fh $out,"\n";
}
input files:
$ cat file1
1.1
$ cat file2
2.1
2.2
$ cat file3
3.1
3.2
3.3
$ cat file4
4.1
4.2
4.3
4.4
output file:
$ cat outfile
1.1 2.1 3.1 4.1
2.2 3.2 4.2
3.3 4.3
4.4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With