【问题标题】:Compare data in first column of a delimited file and print out unique found in second file比较分隔文件第一列中的数据并打印出在第二个文件中找到的唯一数据
【发布时间】:2015-06-04 00:15:28
【问题描述】:

我需要帮助来编写一个可以运行的 perl 脚本,该脚本执行相同的功能 排序命令:sort –t’;’ –k1,1 File1.txt File2.txt File2.txt | uniq –u

我有两个用分号分隔的文件。我需要仅根据 File2.txt 的第一列(数字)的唯一性(而是差异)提取唯一行,同时其他 column2 和 column3 无关紧要。

File1.txt(主文件)

123;winter;season
456;fall;season
789;autumn;season
321;summer;season
654;dry;weather
987;cold;weather

文件2.txt

123;winter;season
456;fall;season
789;autumn;season
321;summer;season
369;march;month
147;september;month

预期输出(369 和 147 不在 File1.txt 中)

369;march;month
147;september;month

到目前为止我已经写了但是它打印出了文件二;

#!/usr/bin/perl

# create names lookup table from first file
open(DATA, "<File1.txt") or die "Couldn't open file File1.txt, $!";
my %names;
while (<DATA>) {
    (my @data)= split /;/, $_;
     $names{$data} = 1;
   last if eof;
}

# scan second file
open(DATA2, "<File2.txt") or die "Couldn't open file File2.txt, $!";
while (<DATA2>) {

    print if /^(\d+)/ && not $data[0];
    }
}

我仍然很难理解数组和哈希。任何有助于改进我的代码的帮助将不胜感激。请添加 cmets 或指出我遇到的任何错误...提前谢谢。,

【问题讨论】:

    标签: perl shell


    【解决方案1】:

    离你不远了。

    • 在第一个循环中,您将分号分隔的字段放入数组@data,然后写入

      $names{$data} = 1;
      

      $data 完全是一个单独的变量,此时未定义。你想要的

      $names{$data[0]} = 1;
      

      使用@data数组的第一个元素

    • 在第二个循环中,您测试了不再存在的 $data[0],因为您在上层循环中声明了 @data。由于您的正则表达式捕获$1 中的第一个字段,您可以说

      print if /^(\d+)/ and not $names{$1};
      

      你的程序会运行

    对于每个 Perl 程序顶部的use strictuse warnings 也是必不可少的。该措施会产生一些有助于解决上述错误的警告消息。您还应该使用词法文件句柄和open 的三参数形式。而且您的last if eof 行是不必要的,因为while 条件无论如何都会为您退出循环。

    这是应用了这些修复程序的重写程序

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    open my $f1_fh, '<', 'File1.txt' or die "Couldn't open file File1.txt: $!";
    my %names;
    while (<$f1_fh>) {
        my @data = split /;/, $_;
        $names{$data[0]} = 1;
    }
    
    open my $f2_fh, '<', 'File2.txt' or die "Couldn't open file File2.txt: $!";
    while ( <$f2_fh> ) {
        print if /^(\d+)/ and not $names{$1};
    }
    

    输出

    369;march;month
    147;september;month
    

    【讨论】:

      猜你喜欢
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多