am with no luck been trying to print all lines between two keywords that I have defined.
Not sure what the heck I am doing wrong.
I have a variable "$linesFromFile" which contains all data from a file. If I print the $linesFromFile I get correct results. Now what I am not getting results for is I am trying to print all lines between the two strings shown below, sometimes the (start and end) strings only appear once, sometimes many times. What I am trying to do is print all lines for every time the two strings are found.
Not sure how to on match and save all lines between to search strings. I tried the save () and print $1 with no luck also.
Thanks for the help in advance.
CODE
for ( $linesFromFile ) {
if ( /^StartTr1/gm .. /^oflTr1/gm ) {
print;
}
}
SAMPLE FILE
CODE
StartTr1
sample 1
sample 1
sample 1
sample 1
SAMPLE 1
oflTr1
nothing
nothing
nothing
StartTr1
sample 2
sample 2
sample 2
sample 2
sample 2
last line before sample 2
oflTr1
junk
junk
junk
RESULTS DESIRED
sample 1
sample 1
sample 1
sample 1
SAMPLE 1
sample 2
sample 2
sample 2
sample 2
sample 2
last line before sample 2
Check Out Our Whitepaper Library. .
The problem is that you have your entire file in one scalar variable, the for loop only executes once, for the entire contents of that variable. You would do better to read the data into an array of lines rather than one scalar, e.g.
CODE
#!/usr/bin/perl -w strict;
#local $/; # slurp mode
@linesFromFile=;
for ( @linesFromFile ) { if ( /^StartTr1/ ... /^oflTr1/ ) { ; } }
__DATA__ StartTr1 sample 1 sample 1 ... However, as you can see, the output of that includes the starting and finishing markers, which you don't want. I'm not sure if there is a cleverer way to do it with range expressions, but I'd probably do something like this:
CODE
$printit=0; for ( @linesFromFile ) { $printit=0 if /^oflTr1/; if $printit; $printit=1 if /^StartTr1/; }
Annihilannic. | |
(Programmer) |
10 Nov 09 2:36 |
Or...
CODE
for($linesFromFile){ while(/^StartTr1(.+?)^oflTr1/gms){ print$1; } | |
阅读(2436) | 评论(0) | 转发(0) |