【问题标题】:How to grep the pair of words from a file?如何从文件中grep这对单词?
【发布时间】:2014-01-21 16:52:31
【问题描述】:

我想在file2 的行中找到file1 的单词对。两个文件中的单词由空格分隔。我想要这对条目,并且顺序无关紧要,这意味着对于文件一中的第二行,这对可以是 STG00001 STG00009 和 STG00009 STG00001 等等。此外,file2 中任何单词对的多次出现也是可以的。

这是我的列表文件 File_1 和一对单词

STG00001 STG00001
STG00001 STG00009
STG00001 STG00012
STG00001 STG00010
STG00001 STG00011

这是File_2,要解析的文件

SML_00001 STG01479 STG00226 RSJ14430.1
SML_00001 STG00001 STG00009 RSJ14430.1
SML_00001 STG00010 STG00001 RSJ14430.1
SML_00002 STG02878 STG02733 RSJ13445.1
SML_00002 STG00001 STG00010 RSJ13445.1
SML_00002 STG02880 STG02733 RSJ13445.1
SML_00002 STG00001 STG00011 RSJ13445.1

生成的文件会是这样的

SML_00001 STG00001 STG00009 RSJ14430.1
SML_00001 STG00010 STG00001 RSJ14430.1
SML_00002 STG00001 STG00010 RSJ13445.1
SML_00002 STG00001 STG00011 RSJ13445.1

【问题讨论】:

  • 您应该尝试编写一些代码并向我们展示您所做的工作。不试就问 - 表现出一些努力。

标签: perl bash shell awk grep


【解决方案1】:
awk 'NR == FNR {a[$1,$2]=1; a[$2,$1]=1; next} ($2 SUBSEP $3) in a' File_1 File_2

【讨论】:

    【解决方案2】:

    以下是一个很好的起点(未经测试,可能有错误...)

    use File::Slurp;
    use Regexp::Assemble;
    
    my $ra = Regexp::Assemble->new;
    
    for my $line (read_file('file1'), chomp => 1) {
       my @symbols = split ' ', $line;
       $ra->add(join ' ', @symbols);
       $ra->add(join ' ', reverse @symbols);
    }
    
    for my $line (read_file('file2') {
       say $line if $line =~ /$ra/;
    }
    

    【讨论】:

      【解决方案3】:

      通过对字段进行排序,可以比较file1和file2。

      #!/usr/bin/perl
      use strict;
      use warnings;
      
      open my $fh1, '<', 'file1.txt' or die $!;
      my %words = map { join('', sort split) => 1} <$fh1>;
      close $fh1 or die $!;
      
      open my $fh2, '<', 'file2.txt' or die $!;
      while (<$fh2>) {
          my $key = join '', sort ( (split)[1,2] );
          print if $words{$key};
      }
      close $fh2 or die $!;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-12
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 2012-03-02
        • 2011-02-22
        相关资源
        最近更新 更多