脚本合并两个文件

时间:2017-03-08 02:51:20

标签: perl hash

我对编码很缺乏经验,但我经常使用Perl合并文件,并在两个文件之间匹配ID和信息。我刚刚尝试使用我之前多次使用的程序来匹配两个文件,但这次它不起作用,我不明白为什么。

以下是代码:

B

以及来自两种输入文件格式的这些片段:

文件1:

use strict;
use warnings;
use vars qw($damID $damF $damAHC $prog $hash1 %hash1 $info1 $ID $sire $dam $F $FB $AHC $FA $hash2 %hash2 $info2);


open (FILE1, "<damF.txt") || die "$!\n Couldn't open damF.txt\n";
my $N = 1;  
while (<FILE1>){
    chomp (my $line=$_);
    next if 1..$N==$.; 
    my ($damID, $damF, $damAHC, $prog) = split (/\t/, $line); 
        if ($prog){
            $hash1 -> {$prog} -> {info1} = "$damID\t$damF\t$damAHC"; 
        }


    open (FILE2, "<whole pedigree_F.txt") || die "$!\n whole pedigree_F.txt \n";
    open (Output, ">Output.txt")||die "Can't Open Output file";

    while (<FILE2>){
        chomp (my $line=$_);
        next if 1..$N==$.; 
        my ($ID, $sire, $dam, $F, $FB, $AHC, $FA) = split (/\t/, $line); 
        if ($ID){
            $hash2 -> {$ID} -> {info2} = "$F\t$AHC"; 
        }
          if ($ID && ($hash1->{$prog})){ 
            $info1 = $hash1 -> {$prog} -> {info1};
            $info2 = $hash2 -> {$ID} -> {info2};
            print "$ID\t$info2\t$info1\n";
        }
    }
}


close(FILE1);

close FILE2;
close Output;

print "Done!\n";

文件2:

501093  0   0   3162
2958    0   0   3163
1895    0   0   3164
1382    0   0   3165
2869    0   0   3166
2361    0   0   3167
754     0   0   3168
3163    0   0   3169

我希望将49327 20543 49325 0.077 0.4899 0.808 0.0484 49328 15247 49326 0.0755 0.5232 0.8972 0.0499 49329 27823 49327 0.0834 0.5138 0.8738 0.0541 的值与column 4 in file 1匹配。

然后我还要打印column 1 in file 2columns 2 and 3 in file 1的匹配值。

此外,值得一提的是每个文件中都有 500000 条目。

这是我得到的输出:

columns 3 and 5 in file 2

请注意,它没有遍历我创建的第一个哈希。

1 个答案:

答案 0 :(得分:1)

在SQLite中创建两个表。将TSV加载到它们中。做一个SQL连接。它会更简单,更快捷。

Refer to this answer about how to load data into SQLite。在您的情况下,您需要.mode tabs

sqlite> create table file1 ( col1 int, col2 int, col3 int, col4 int );
sqlite> create table file2 ( col1 int, col2 int, col3 int, col4 numeric, col5 numeric, col6 numeric, col7 numeric );
sqlite> .mode tabs
sqlite> .import /path/to/file1 file1
sqlite> .import /path/to/file2 file2

有很多方法可以改进这些表格,但我不知道你的数据是什么。使用更好的名称。您还需要声明主键和外键之类的内容以及indexes来加快速度。

现在,您可以使用众所周知的查询语言轻松处理数据,而不是一堆自定义代码。

  

我想匹配文件1中第4列的值和文件2中的第1列。

     

然后我还要打印文件1中第2列和第3列以及文件2中第3列和第5列的匹配值。

您可以在两个表之间使用SQL join执行此操作。

select file1.col2, file1.col3, file2.col3, file2.col5
from file1
join file2 on file1.col4 = file2.col1
相关问题