搜索特定的重复ID

时间:2012-07-09 11:36:30

标签: perl duplicates

我编写了一个perl脚本,它读入2个不同的文件,比较这两个文件中的ID,只打印出ID匹配的数据。 ID文件被读入数组,而数据文件则逐行读取。这一切都很好,但现在我需要添加更多。在我的数据文件中,我有时会有重复ID的行,因为主题已经多次访问以提供样本。因此,我需要查看这些重复内容,并仅查看最新的访问日期。

所以我的数据文件看起来像这样:

   ID  DOV  Data1  Data2 etc etc

现在我已经看到哈希是搜索重复项的方法,但是我看到的所有修复都只是简单地删除了重复项,这不是我想要的。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这将显示每个ID的最后一个DOV,对输入数据进行批次假设,因此很有可能它不会为您提供开箱即用的功能。 (特别是,如果您的输入数据没有按日期排序,它根本不起作用,因为它只需要查看每个ID的最后日期。另外,如果日期的格式是包含空格的方式,例如“ “7月9日星期一15:51:22 CEST 2012”,它只会将日期提升到第一个空格(本例中为“Mon”)。)这里的重点是演示基本技术,而不是提供完整的解决方案

#!/usr/bin/env perl    

use strict;
use warnings;

my %visit;
while (<DATA>) {
  my ($id, $date) = split;
  $visit{$id} = $date;
} 

for my $id (sort keys %visit) {
  print "$id => $visit{$id}\n";
} 

__DATA__
1       2012-01-01
2       2012-01-02
1       2012-02-03
3       2012-02-04
2       2012-03-05
3       2012-03-06
4       2012-04-07
1       2012-04-08
5       2012-05-09
1       2012-05-10

答案 1 :(得分:0)

# read id file
my %id_hash;
while (<IDFILE>) {
  chomp;
  $id_hash{$_} = 1;
}

#read data file
while (<DATAFILE>) {
  my @arr = split(/\s+/, $_);
  if (defined $id_hash{$arr[0]}) { # only process if exists in id file
    # and only if this is the first data entry or a later visit
    if ( (not ref $id_hash{$arr[0]}) or ($id_hash{$arr[0]}[1] < $arr[1]) ) {
      # store all data in an array ref
      $id_hash{$arr[0]} = [ @arr ];
    }
  }
}

for my $id (keys %id_hash) {
  print join(" ", @{$id_hash{$id}}), "\n";
}