perl脚本,用于删除其下方的字符和行

时间:2018-12-25 15:49:22

标签: perl

PIN W[2]
DIRECTION INPUT ;
USE SIGNAL ;
PORT
LAYER M5
        RECT 0.115 0.59 0.175 1.22 ;
        RECT 0.06 0.98 0.175 1.22 ;
        RECT 0.335 1.16 0.395 1.44 ;
        RECT 0.51 0.57 0.63 0.65 ;
LAYER M3
        RECT 0.115 0.59 0.175 1.22 ;
        RECT 0.06 0.98 0.175 1.22 ;
        RECT 0.335 1.16 0.395 1.44 ;
        RECT 0.51 0.57 0.63 0.65 ;
LAYER M1
        RECT 0.115 0.59 0.175 1.22 ;
        RECT 0.06 0.98 0.175 1.22 ;
        RECT 0.335 1.16 0.395 1.44 ;
        RECT 0.51 0.57 0.63 0.65 ;
LAYER M6
        RECT 0.115 0.59 0.175 1.22 ;
        RECT 0.06 0.98 0.175 1.22 ;
        RECT 0.335 1.16 0.395 1.44 ;
        RECT 0.51 0.57 0.63 0.65 ;
END
END W[2]

我想要的是搜索以LAYER M开头的数字(上面有最大的数字),并仅打印下面以RECT开头的行。请参考下面的代码片段,以了解所需行的外观。

PIN W[2]
DIRECTION INPUT ;
USE SIGNAL ;
PORT
LAYER M6
        RECT 0.115 0.59 0.175 1.22 ;
        RECT 0.06 0.98 0.175 1.22 ;
        RECT 0.335 1.16 0.395 1.44 ;
        RECT 0.51 0.57 0.63 0.65 ;
END
END W[2]

2 个答案:

答案 0 :(得分:2)

我发现不两次浏览文件比较容易, 行号往往使我感到困惑,所以我决定发表自己的看法。

祝您好运,随时可以评论要修改的任何改进!

#!/usr/bin/env perl
use strict;
use warnings;

open my $fh, '<', 'input.txt' or die "Cannot open file < '$input_fn': $!";

my %layers;

my $layer_number;

my ( $begin_block, $end_block );

while ( my $line = <$fh> ){

    if ( $line =~ /^[\s\t]*LAYER\s+M([0-9]+)/ ){
        $layer_number = $1;
    }

    # layer number not set: Add to begin block
    unless ( $layer_number ){
        $begin_block .= $line;
        next;
    }

    # END: no further layers. Just slurp it and done.
    if ( $line =~ /END/ ){
        my $slurped_end = do{ local $/; <$fh>; };
        $end_block = $line . $slurped_end;
        last;
    }

    # store line for this block
    $layers{ $layer_number } .= $line;
}

close $fh;

# find highest block, reassemble and print
my $highest_block_number = ( sort{ $a <=> $b } keys %layers )[-1];

print $begin_block . $layers{ $highest_block_number } . $end_block;

答案 1 :(得分:1)

这里是一个例子。它将扫描文件file.txt的行两次。第一次记录最大层数,第二次记录不是层或最大层​​块时打印行:

use strict;
use warnings;

my $fn = 'file.txt';
my @lines;
my $max_layer_num = 0;
open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
while (<$fh>) {
    push @lines, $_;
    if ( /^LAYER\s+M(\d+)/ ) {
        $max_layer_num = $1 if $1 > $max_layer_num;
    }
}
close $fh;
my $i = 0;
while ( $i <= $#lines ) {
    $_ = $lines[$i];
    if( /^LAYER\s+M(\d+)/ ) {
        if ( $1 != $max_layer_num ) {
            while (1) {
                $i++;
                last if $i > $#lines;
                $_ = $lines[$i];
                last if $_ !~ /^\s+RECT/;
            }
            next;
        }
    }
    print; $i++
}