in reply to Re^2: Question on RE based matching
in thread Question on RE based matching
Your (main) problem is that you're matching against individual lines, i.e. 'HEADER(', next ' LIBDAT("GTASK")', and so on. In other words, the regex can never find 'HEADER...' and 'GENRE_BY...' at the same time.
One way around this would be to split the input appropriately (as shown in the snippet by GrandFather). Another way would be to use the flip-flop operator .. to accumulate the necessary lines as shown below. The expression if (/^HEADER/ .. /^\)/) is true starting with a line matching /^HEADER/ up until a line matching /^\)/, in which case you append the current line to the accumulator ($entry). Upon the next line (not being HEADER or )) the flip-flop is reset to false.
(I've put in an additional end-of-entry test (if (/^\)), so the code will correctly deal with the case where a new HEADER line is immediately following a previous entry (without any other lines in between) — if your input always has other stuff in between the entries, you could also just put the regex test directly in an else branch of the flip-flop test...)
#!/usr/bin/perl use strict; use warnings; use Getopt::Long; GetOptions( 'FileIn=s' => \my $fileIn, 'FileOut=s' => \my $fileOut, ); if ($fileIn && $fileOut) { open(INPUT,"<","$fileIn"); my $entry = ""; while (<INPUT>) { next if /^\n/; if (/^HEADER/ .. /^\)/) { # flip-flop $entry .= $_; # accumulate input } if (/^\)/) { # end of entry # check for desired type of entry if ($entry =~ /^HEADER(.*?)^\s*GENRE_BY(.*)/sm) { print $entry; } $entry = ""; # reset accumulator } } }
|
|---|