【问题标题】:perl script to find matching lines in two filesperl 脚本在两个文件中查找匹配的行
【发布时间】:2015-04-04 15:29:06
【问题描述】:

我有两个看起来像(如下)的文件,并且想要从第二个文件中的第一个文件中查找字段,但打印第二个文件的每个字段。

#rs116801199 720381
#rs138295790 16057310
#rs131531 16870251
#rs131546 16872281
#rs140375 16873251
#rs131552 16873461

#--- rs116801199 720381 0.026 0.939 0.996 0 -1 -1 -1
#1 rs12565286 721290 0.028 1.000 1.000 2 0.370 0.934 0.000
#1 rs3094315 752566 0.432 1.000 1.000 2 0.678 0.671 0.435
#--- rs3131972 752721 0.353 0.906 0.938 0 -1 -1 -1
#--- rs61770173 753405 0.481 0.921 0.950 0 -1 -1 -1

我的脚本如下:

#! perl -w

my $file1 = shift@ARGV;

my @filtered_snps;
open (IN, $file1) or die "couldn't read file one";
while(<IN>){
    my@L=split;
    #next if ($L[0] =~ m/peak/);
    push @filtered_snps,[$L[0],$L[1]];

}
close IN;

my $file2 = shift@ARGV;

my @snps;
open (IN, $file2);
while (<IN>){
    my@L=split;
    foreach (@filtered_snps){

        if (($L[1] eq ${$_}[0]) && ($L[2] == ${$_}[1])) {

            print "@L\n";

            next;
        }
    }
}

当我应该从文件 1 中找到每一行时,我没有得到任何输出。我也尝试了 grep,但没有成功。

【问题讨论】:

    标签: perl string-matching


    【解决方案1】:

    在第一个 while 中,您分配给错误的数组,您的意思是 @L 这里。

    然后,您的第一个数组(来自第一个文件)和其他数组中有完全不同的字符串。尝试在您的 for-iteration 中将它们都打印出来。你会发现它们无法匹配。

    【讨论】:

      【解决方案2】:

      从第一个文件创建项目的哈希表,然后遍历第二个文件并检查该 rs-name 是否存在...我也在确认该数字与名称匹配。

      use strict;
      use warnings;
      
      my %hash;
      my $regex = qr/#.* *(rs\d+) (\d+) *.*/;
      
      open my $file1, '<', shift @ARGV;
      while (<$file1>) {
          my ($name, $num) = $_ =~ $regex;
          $hash{$name} = $num;
      }
      close $file1;
      
      open my $file2, '<', shift @ARGV;
      while (<$file2>) {
          my ($name, $num) = $_ =~ $regex;
          print if (exists $hash{$name} and $hash{$name} = $num)
      }
      close $file2;
      

      【讨论】:

      • 问题是我确定 file1 中的所有名称都存在于 file2 中。我只需要拉出 file2 中具有这些 rsID 和数字的行。 File2 比 file1 大得多,并且有我不想要的其他 rsID。
      • 这正是我的脚本所做的......它打印file2中存在于file1中的行。它不会打印 file2 中不在 file1 中的行。
      猜你喜欢
      • 2015-09-20
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 2018-09-06
      • 2015-08-16
      • 1970-01-01
      • 2020-03-03
      相关资源
      最近更新 更多