How do I extract lines between two line delimiters in Perl?

前端 未结 6 1732
醉酒成梦
醉酒成梦 2020-12-09 06:23

I have an ASCII log file with some content I would like to extract. I\'ve never taken time to learn Perl properly, but I figure this is a good tool for this task.

Th

6条回答
  •  甜味超标
    2020-12-09 06:50

    Not too bad for coming from a "virtual newcommer". One thing you could do, is to put the "$found=1" inside of the "if($found == 0)" block so that you don't do that assignment every time between $start and $stop.

    Another thing that is a bit ugly, in my opinion, is that you open the same filehandler each time you enter the $start/$stop-block.

    This shows a way around that:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $start='CINFILE=$';
    my $stop='^#$';
    my $filename;
    my $output;
    my $counter=1;
    my $found=0;
    
    while (<>) {
    
        # Find block of lines to extract                                                           
        if( /$start/../$stop/ ) {
    
            # Start of block                                                                       
            if( /$start/ ) {
                $filename=sprintf("boletim_%06d.log",$counter);
                open($output,'>>'.$filename) or die $!;
            }
            # End of block                                                                         
            elsif ( /$end/ ) {
                close($output);
                $counter++;
                $found = 0;
            }
            # Middle of block                                                                      
            else{
                if($found == 0) {
                    print $output (split(/ /))[1];
                    $found=1;
                }
                else {
                    print $output $_;
                }
            }
    
        }
        # Find block of lines to extract                                                           
    
    }
    

提交回复
热议问题