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

前端 未结 6 1693
醉酒成梦
醉酒成梦 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:27

    After Telemachus' reply, things started pouring out. This works as the solution I'm looking at after all.

    1. I'm trying to extract lines delimited by two strings (one, with a line ending with "CINFILE="; other, with a line containing a single "#") in separate lines, excluding the delimiter lines. This I can do with Telemachus' solution.
    2. The first line has a space I want to remove. I'm also including it.
    3. I'm also trying to extract each line-set into separate files.

    This works for me, although the code can be classified as ugly; this is because I'm currently a virtually newcomer to Perl. Anyway here goes:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    my $start='CINFILE=$';
    my $stop='^#$';
    my $filename;
    my $output;
    my $counter=1;
    my $found=0;
    
    while (<>) {
      if (/$start/../$stop/) {
        $filename=sprintf("boletim_%06d.log",$counter);
        open($output,'>>'.$filename) or die $!;
        next if /$start/ || /$stop/;
        if($found == 0) { print $output (split(/ /))[1]; }
        else { print $output $_; }
        $found=1;
      } else { if($found == 1) { close($output); $counter++; $found=0; } }
    }
    

    I hope it benefits others as well. Cheers.

提交回复
热议问题