Awk - 从包含另一个文件中描述的范围内的值的文件中获取行

时间:2016-07-25 15:49:31

标签: perl shell awk

我有2个制表符分隔的文件格式与此类似:

档案1

A 100 90 PASS
B 89 80 PASS
C 79 70 PASS
D 69 60 FAIL
F 59 0 FAIL

文件2

Randy 80
Denis 44
Earl 97

我想从文件2中的第2列获取值,并将它们与文件1的第2列和第3列之间给出的范围进行比较。然后我想创建一个组合此数据的新文件,从第1列和第2列打印文件2和文件1中的第1列和第4列:

文件3

Randy 80 B PASS
Denis 44 F FAIL
Earl 97 A PASS

我想用awk或perl实现这个。

3 个答案:

答案 0 :(得分:3)

你可以使用这个awk:

awk 'BEGIN{FS=OFS="\t"}
FNR==NR {
   a[$0] = $2
   next
}
{
   for (i in a)
      if ($2>=a[i] && $3<=a[i])
         print i, $1, $4
}' file2 file1
Earl    97  A   PASS
Randy   80  B   PASS
Denis   44  F   FAIL

答案 1 :(得分:2)

在perl中,我可能会做这样的事情:

#!/usr/bin/env perl
use strict;
use warnings 'all';
use Data::Dumper;

open ( my $grades_in, '<', "file1.txt" ) or die $!;
my @grade_lookup = map { [split] } <$grades_in>;
print Dumper \@grade_lookup;
close ( $grades_in ); 

open ( my $people, '<', "file2.txt" ) or die $!; 
while (<$people>) {
   chomp;
   my ( $person, $score ) = split;
   my ( $grade ) = grep { $_ -> [1] >= $score 
                     and $_ -> [2] <= $score } @grade_lookup;
   print join " ", $person, $score, $grade -> [0], $grade -> [3], "\n";
} 
close ( $people ); 

输出:

Randy 80 B PASS 
Denis 44 F FAIL 
Earl 97 A PASS 

答案 2 :(得分:2)

在Perl中

use strict;
use warnings 'all';
use autodie;

use List::Util 'first';

my @grades = do {
    open my $fh, '<', 'file1.txt';
    map [ split ], <$fh>;
};

open my $fh, '<', 'file2.txt';

while ( <$fh>) {
    my ($name, $score) = split;
    my $grade = first { $_->[2] <= $score } @grades;
    print "$name $score @$grade[0,3]\n";
}

输出

Randy 80 B PASS
Denis 44 F FAIL
Earl 97 A PASS