5

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

4 回答 4

4

据我了解,您可以同时为两个文件读取一行并打印用制表符分隔的每一行,例如:

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

如果文件的行数不同,此脚本将不起作用。对于这种情况,您将需要另一种方法。

于 2012-07-05T09:02:17.433 回答
2

你可以简单地在 shell 中做到这一点:cat file1.txt file2.txt file3.txt > selected.txt

或者在 Perl 中:

use strict;

@ARGV = ('file1.txt', 'file2.txt', 'file3.txt');

open MULTI, '>', 'selected.txt' 
    or die $!;

while (<>) {
    print MULTI;
}
于 2012-07-05T09:03:23.127 回答
2

怎么样:

#!/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";
}

输入文件:

$ 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

输出文件:

$ cat outfile 
1.1     2.1     3.1     4.1
        2.2     3.2     4.2
                3.3     4.3
                        4.4
于 2012-07-05T09:40:33.890 回答
0

此脚本专注于 IO::File 的高性能,并且仅适用于在同一行上至少有一些非空白文本的文件。

#!/usr/bin/perl
use IO::File;
@f= map { IO::File->new($_) } @ARGV;
print $q,qq(\n) until ($q=join (qq(\t), map { m{(.*)} && $1 } map { $_->getline } @f))=~m{^\t+$}
于 2012-07-09T04:18:24.330 回答