提取连续值并打印所有行

时间:2012-03-02 11:06:43

标签: perl

如果值连续超过4行(如果col1中的值相同),我想提取行,但是应该打印所有行(应该打印超过4行)。

如果col1中的值相等,并且col2和col3中的值连续(如连续数字)超过接下来的4行,则返回这些行。线的col3中的值可以相等,或者可以通过下一行的col2值最小为100。

这里连续并不意味着1行(在1行col3-col2中)。它表示行的col3值与下一行的col2值相比。

我的档案是 - >

A   0    100
A1  0    100
A1  100  200
A1  200  300
A1  400  500
A1  500  600
A1  600  700
A1  700  800
A1  1600 1700
A2  100  200
A2  200  300
A2  400  500
A2  500  600
A2  600  700
A3  800  900

期望的输出是 - >

A1  0    100
A1  100  200
A1  200  300
A1  400  500
A1  500  600
A1  600  700
A1  700  800
A2  100  200
A2  200  300
A2  400  500
A2  500  600
A2  600  700

这是另外一个例子 - >我的输入文件 - >

A   0    100
A1  0    100
A1  100  200
A1  200  300
A1  500  600
A1  600  700
A1  700  800
A1  1600 1700
A2  100  200
A2  200  300
A2  400  500
A3  800  900

输出 - >

“没有连续线”。

现在没有输出,因为与下一行相比,应该有超过4行具有相同的col1值,并且这些行的col3值应该等于或小于100。

到目前为止,我试过这个但是没有用 - >

use strict;
use warnings;

*ARGV or die "No input file specified";
open *first, '<',$ARGV[0] or die "Unable to open input file: $!";
my @data;
while (<first>) {

     if (not @data) {
     @data = split;
     next;
     }

     my @new = split /\s+/;

     if ($new[0] eq $data[0] and $new[1] <= $data[2]+ 100) {
     $data[2] = $new[2];
          if ( $data[2] - $data[1] >= 500){
             print join("\t", @new), "\n";
          }
     }

    else {
    @data = @new;
    }
}

请帮助。

1 个答案:

答案 0 :(得分:2)

怎么样:

#!/usr/bin/perl 
use strict;
use warnings;
use Data::Dump qw(dump);
use 5.010;

$_ = <DATA>;
chomp;
my ($p_key, $p_col1, $p_col2) = split;
my @result = ($_);
open my $fh, '>', 'path/to/output_file' or die "unable to open file:$!";
while(<DATA>) {
    chomp;
    my ($key, $col1, $col2) = split;
    if ($key eq $p_key) {
        if ($col1 <= $p_col2+100) {
            push @result, $_;
        } else {
            print_to_file($fh, \@result) if (@result > 3);
            @result = ();
        }
    } else {
        print_to_file($fh, \@result) if (@result > 3);
        @result = ($_);
    }
    ($p_key, $p_col2) = ($key, $col2);
}
print_to_file($fh, \@result) if (@result > 3);

sub print_to_file {
    my $fh = shift;
    my $res = shift;
    while(@$res) {
        print $fh, $_, "\n";
    }
}
__DATA__
A   0    100
A1  0    100
A1  100  200
A1  200  300
A1  400  500
A1  500  600
A1  600  700
A1  700  800
A1  1600 1700
A2  100  200
A2  200  300
A2  400  500
A2  500  600
A2  600  700
A3  800  900

<强>输出:

(
  "A1  0    100",
  "A1  100  200",
  "A1  200  300",
  "A1  400  500",
  "A1  500  600",
  "A1  600  700",
  "A1  700  800",
)
(
  "A2  100  200",
  "A2  200  300",
  "A2  400  500",
  "A2  500  600",
  "A2  600  700",
)
相关问题