【问题标题】:comparing two files and display matched results比较两个文件并显示匹配的结果
【发布时间】:2013-11-26 05:17:26
【问题描述】:

我有以下问题要解决...我有两个包含以下信息的文件:

一个.txt

alan, 23, alan@yahoo.com
albert, 27, albert@yahoo.com

b.txt

alan:173:analyst
victor:149:director
albert:171:clerk
coste:27:driver

我需要从两个文件的每一行中提取名称(零字段),比较它们,如果它们匹配,打印年龄和职业信息。 因此,我的输出应该是:

alan, 23, analyst
albert, 27, clerk

到目前为止我得到了什么,但它不起作用:

open F2, 'a.txt' or die $!;
@interesting_lines = <F2>;

foreach $line (@interesting_lines ) {
    @string = split(', ', $line);
    print "$string[0]\n";
}
close F2;

open F1, 'b.txt' or die $!;
while (defined(my $line = <F1>)) {
    @string2 = split(':', $line);
    print $string2[0];
    print "$.:\t$string2[0]" if grep {$string2[0] eq $_} $string[0] ;
}

有人知道如何实现我的要求吗?谢谢... Ps,bith 文件的行数可能比我发布的要多,但文件 b.txt 将始终包含文件 a.tx 的所有名称,以及额外的行数。

【问题讨论】:

    标签: perl


    【解决方案1】:
    open my $F2, '<', 'a.txt' or die $!;
    chomp(my @interesting_lines = <$F2>);
    close $F2;
    
    my %dic;
    foreach my $line (@interesting_lines) {
      my ($name, @arr) = split(/, /, $line);
      $dic{$name} = \@arr;
    }
    
    open my $F1, '<', 'b.txt' or die $!;
    
    while (my $line = <$F1>) {
      chomp($line);
      my ($name, $pos) = ( split(/:/, $line) )[0, 2];
    
      my $arr = $dic{$name} or next;
      printf("%s, %s, %s, %s\n", $name, $arr->[0], $pos, $arr->[1]);
    }
    close $F1;
    

    【讨论】:

    • 非常感谢您的帮助:)
    • mpapec,非常感谢。是的,更新版本完美运行。非常感谢。
    • @WisdomSeeker 您通过单击答案左侧的复选框来接受答案
    • 哦,抱歉,不知道。我最近才开始使用这个论坛,哈哈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多