输入file1:它包含下限和上限
1: 3 5
2: 4 7
3: 8 10
4: 5 10
5: 10 15
6: 10 20
7: 15 30
8: 30 40
输入文件2:它包含某些值
a 3
b 4
c 6
d 7
文件3:它还包含一些值
a 9
b 12
c 36
d 23
输出:
1 a b file2
2 b c d file2
3
4 c d file2
5 b file3
6 b file3
7 d file3
8 c d file3
我有三个档案。 file1包含范围,file2或file3包含某些值。现在我们必须从文件1中检查它们的间隔id并打印输出以获得命中,即, 如果值属于任何间隔,则它必须打印间隔id,值id及其来源的文件。
#!/bin/usr/perl -w
use strict ;
open (R1,"$file1.txt")|| die;
open (R2,"$file2.txt")|| die;
open (R3,"$file3.txt")|| die;
while (($lin1=<R1>) && ($line=<R2>) && ($line3= <R3>)){
my $i;
坚持到这里..如何检查天气文件2的特定值和file3属于哪个以及file1中的间隔数
答案 0 :(得分:3)
只是另一种方法。
#!/usr/bin/perl
use strict;
use warnings;
open my $fh2, '<', 'file2' or die $!;
my %hash2 = map split, <$fh2>;
close $fh2 or die $!;
open my $fh3, '<', 'file3' or die $!;
my %hash3 = map split, <$fh3>;
close $fh3 or die $!;
open my $fh1, '<', 'file1' or die $!;
while (<$fh1>) {
my ($id, $min, $max) = split;
my @letters2 = grep $hash2{$_} >= $min && $hash2{$_} <= $max,
sort keys %hash2;
my @letters3 = grep $hash3{$_} >= $min && $hash3{$_} <= $max,
sort keys %hash3;
print join(" ", $id, @letters2,
@letters2 ? 'file2' : (),
@letters3,
@letters3 ? 'file3' : ()
), "\n";
}
close $fh1 or die $!;
打印
1: a b file2
2: b c d file2
3: a file3
4: c d file2 a file3
5: b file3
6: b file3
7: d file3
8: c file3
更新:一种更好的方法,可以提供超过2个文件
#!/usr/bin/perl
use strict;
use warnings;
my %name_num;
my @file = qw/file2 file3/;
for my $file (@file) {
open my $fh, '<', $file or die $!;
%{ $name_num{$file} } = map split, <$fh>;
}
open my $fh1, '<', 'file1' or die $!;
while (<$fh1>) {
my ($id, $min, $max) = split;
print $id;
for my $file (@file) {
my @letters =
grep $name_num{$file}{$_} >= $min && $name_num{$file}{$_} <= $max,
sort keys %{$name_num{$file}};
if (@letters) {
print join(" ", '', @letters, $file);
}
}
print "\n";
}
close $fh1 or die $!;
答案 1 :(得分:0)
你可以尝试这个perl脚本:
#! /usr/bin/perl
use v5.12;
use autodie;
my @files=qw(file2 file3);
my %val;
for my $file (@files) {
open (my $fh, "<", $file);
while (my $line=<$fh>) {
my ($id, $val)=$line=~/(\S+)\s+(\d+)/;
$val{$file}=[] if (! exists $val{$file});
push (@{$val{$file}},{id=>$id, val=>$val});
}
close($fh);
}
my @iv;
open (my $fh, "<", "file1");
while (my $line=<$fh>) {
my ($id,$start,$end)=$line=~/(\d+):\s+(\d+)\s+(\d+)/;
my %h=();
for my $file (@files) {
my $str="";
for my $vv (@{$val{$file}}) {
my $v=$vv->{val};
if ($v>=$start && $v<=$end) {
$str=$str." ".$vv->{id};
}
}
$h{$file}=$str if $str;
}
$h{id}=$id;
push (@iv,\%h);
}
close($fh);
for (@iv) {
my $int=$_;
print $int->{id};
for my $file (@files) {
if (exists $int->{$file}) {
print "\t",$int->{$file},"\t",$file;
}
}
print "\n";
}
输出:
1 a b file2
2 b c d file2
3 a file3
4 c d file2 a file3
5 b file3
6 b file3
7 d file3
8 c file3