Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello again,
I have a data file that I need to parse similar to the one below
group: device_info In ; 10 ; 0x0 ; 0x100cd ; .1 Out ; 10 ; 0x0 ; 0x100d3 ; .1 In ; 20 ; 0x0 ; 0x500c4 ; .1 Out ; 20 ; 0x0 ; 0x500d4 ; .1 data: None IP: 1.2.3.4
I need to grab everyline between the "group:" line and the"data:" line excluding all the new lines.

I.E.
In ; 10 ; 0x0 ; 0x100cd ; .1 Out ; 10 ; 0x0 ; 0x100d3 ; .1 In ; 20 ; 0x0 ; 0x500c4 ; .1 Out ; 20 ; 0x0 ; 0x500d4 ; .1
Any suggestions?

Replies are listed 'Best First'.
Re: File Parsing
by pfaut (Priest) on Dec 07, 2002 at 00:48 UTC
    #!/usr/bin/perl -w use strict; my $outside=1; while (<>) { $outside = 0, next if (/^group:/); $outside = 1, next if (/^data:/); print unless $outside || /^\s*$/; }

    Update: changed + to * in the print line's regex.

Re: File Parsing
by cjf-II (Monk) on Dec 07, 2002 at 00:47 UTC
Re: File Parsing
by runrig (Abbot) on Dec 07, 2002 at 01:00 UTC
    By exclude "new lines" I assume you mean "blank lines" ?
    while (<>) { if (my $stat = /^group:/../^data:/) { print unless /^\s*$/ or $stat == 1 or $stat =~ /E/; } }
    Update:Fixed during pfaut's reply to this node :-)

      I think he only wanted the lines between the group and data lines. Your version prints out those lines.

        Yes I did,
        Thank You
Re: File Parsing
by slife (Scribe) on Dec 07, 2002 at 22:25 UTC

    Here's an alternative method involving grep and split:

    local $/; my $data = <DATA>; my @found = grep /^[IO]/ => split /\n/ => $data; print map { join '' => $_, "\n", } @found; # or whatever. __DATA__ group: device_info In ; 10 ; 0x0 ; 0x100cd ; .1 Out ; 10 ; 0x0 ; 0x100d3 ; .1 In ; 20 ; 0x0 ; 0x500c4 ; .1 Out ; 20 ; 0x0 ; 0x500d4 ; .1 data: None