繁体   English   中英

基于Perl中的一列合并多个文本文件

[英]Merging multiple text files based on one column in perl

我是Perl的新手,这是我在本博客中希望解决的第一个问题。

我在文件夹中有一些文本(10-18)文件,我想读取所有文件并合并所有在Names列中具有通用变量的文件以及所有文件的Area列。 例如:文件1.txt

名称sim Area Cas
氨基酸12 54 222
抗体23 2 343
氨基酸32 34 34
工商管理硕士54 76 65

文件2.txt

名称Sim Area Cas
ab 45 45 56
abc 76 87 98
工商管理硕士54 87 87
氨基酸33 43 54

文件3.txt

名称Sim Area Cas

氨基酸43 54 65
ab 544 76 87
交流54 65 76

输出应为

名称Area1 Area2 area3
氨基酸32 43 54
抗体23 45 76

任何人都可以为此提供帮助。 我是Perl的新手,正在努力使用哈希。

到目前为止,我已经尝试过了

use strict;
use warnings;

my $input_dir = 'C:/Users/Desktop/mr/';
my $output_dir = 'C:/Users/Desktop/test_output/';

opendir SD, $input_dir || die 'cannot open the input directory $!';
my @files_list = readdir(SD);
closedir(SD);

    foreach my $each_file(@files_list)
    {
        if ($each_file!~/^\./)               
        {
            #print "$each_file\n"; exit;
            open (IN, $input_dir.$each_file) || die 'cannot open the inputfile $!';
            open (OUT, ">$output_dir$each_file") || die 'cannot open the outputfile $!';

        print OUT "Name\tArea\n"; 

            my %hash; my %area; my %remaning_data;

            while(my $line=<IN>){
            chomp $line;


            my @line_split=split(/\t/,$line);
            # print $_,"\n" foreach(@line_split);

            my $name=$line_split[0]; 
             my $area=$line_split[1]; 
                }
            }   
        }

谁能提供有关如何完成此操作的指南? 提前致谢。

perl -lane '$X{$F[0]}.=" $F[2]";END{foreach(keys %X){if(scalar(split / /,$X{$_})==4){print $_,$X{$_}}}}' file1 file2 file3

测试:

> perl -lane '$X{$F[0]}.=" $F[2]";END{foreach(keys %X){if(scalar(split / /,$X{$_})==4){print $_,$X{$_}}}}' file1 file2 file3
ab 2 45 76
aaa 34 43 54
#!/usr/bin/perl

use strict;
use warnings;

my $inputDir = '/tmp/input';
my $outputDir = '/tmp/out';

opendir my $readdir, $inputDir || die 'cannot open the input directory $!';
my @files_list = readdir($readdir);
closedir($readdir);

my %areas;
foreach my $file (@files_list) {
    next if $file =~ /^\.+$/; # skip ..
    open (my $fh, "<$inputDir/$file");
    while (my $s = <$fh>) {
        if ($s =~ /(\w+)\s+[\d\.]+\s+([\d\.]+)/) {
            my ($name,$area) = ($1, $2); # parse name and area
            push(@{$areas{$name}}, $area); # add area to the hash of arrays
        }
    }
    close ($fh);
}

open (my $out, ">$outputDir/outfile");
foreach my $key (keys %areas) {
    print $out "$key ";
    print $out join " ", @{$areas{$key}};
    print $out "\n";
}
close ($out);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM