Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Printing lines after regexp match until match of a different regexp

by turbolofi (Acolyte)
on Jun 14, 2009 at 16:23 UTC ( #771432=perlquestion: print w/replies, xml ) Need Help??
turbolofi has asked for the wisdom of the Perl Monks concerning the following question:

Hi fellow monks I am struggling with a small problem - I want to print the text following a match from a regular expression, until a match of a different regular expression.
The input is this:
CR *FDA, 1997, GUID IND EXT REL OR BADAWY SIF, 1996, INT J PHARM, V128, P45 (more lines w. similar formatting) NR 42
Text with similar formatting is repeated many times in the input - I'd like to print everything between "CR " and "NR" - in all occurences in the file. The code I have thus far is this:
use strict; use warnings; my @infile = (<>); my ($citedreferences, $line); my $n = 0; foreach $line (@infile){ if ($line =~ m{^CR .+}gsi){ do{ $n++; print $n . $line; next; } until ($line =~ m{^NR}gsi) } };

However, this only prints the lines matching the first regular expression. Any tips to point me in the right direction would be much appreaciated

Replies are listed 'Best First'.
Re: Printing lines after regexp match until match of a different regexp
by JavaFan (Canon) on Jun 14, 2009 at 16:31 UTC
    Use the flipflop operator:
    while (<DATA>) { print if /CR/ .. /NR/; } __DATA__ foo bar foo CR *FDA, 1997, GUID IND EXT REL OR BADAWY SIF, 1996, INT J PHARM, V128, P45 (more lines w. similar formatting) NR 42 more text CR yada yada yada yada yada NR 17 rubbish
    Output:
    CR *FDA, 1997, GUID IND EXT REL OR BADAWY SIF, 1996, INT J PHARM, V128, P45 (more lines w. similar formatting) NR 42 CR yada yada yada yada yada NR 17
      Haha, so simple. Fantastic. Thanks a bunch!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://771432]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2018-08-17 01:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:









    Results (174 votes). Check out past polls.

    Notices?