On Jan 18, 10:27 am, [EMAIL PROTECTED] (Rob Dixon) wrote:
> Gunnar Hjalmarsson wrote:
> > [EMAIL PROTECTED] wrote:
> >> On Jan 14, 5:08 pm, [EMAIL PROTECTED] (Gunnar Hjalmarsson) wrote:
> >>> [EMAIL PROTECTED] wrote:
> >>>> I have a large text file with
> >>>> information essentially broken into lines like this:
>
> >>>> findable text with a regexp
> >>>> information I care about
> >>>> more findable text
>
> >>>> There are plenty of sections like this in the file. How can I write a
> >>>> program that opens the file then searches for the middle line and
> >>>> prints it to a new file?
>
> >>>      open my $IN,  '<', 'infile.txt' or die $!;
> >>>      open my $OUT, '>', 'outfile.txt' or die $!
> >>>      while ( <$IN> ) {
> >>>          print $OUT scalar <$IN> if /^findable/;
> >>>      }
>
> >> OK here's what I've got:
>
> >> #!/usr/local/bin/perl
> >> use strict;
> >> use warnings;
>
> >> open (OUT, ">output.txt") or die "Couldn't open output: $!";
> >> open (IN, "input.txt") or die "Couldn't open input: $!";
>
> >> while (<IN>) {
> >>     print OUT $_;
> >> }
>
> >> close OUT;
> >> close IN;
>
> >> This (obviously) copies the whole text file. How can I select only
> >> certain lines to copy based on either the line above or below it?
>
> > I suggested a solution. Why do you ignore my suggestion and repeat your
> > question?
>
> Your suggestion didn't tell him how to solve his problem Gunnar.
>
> A construct like the program below may help.
>
> Rob
>
> use strict;
> use warnings;
>
> my $wanted;
>
> while (<DATA>) {
>    if (/findable text with a regexp/) {
>      $wanted = 1;
>    }
>    elsif (/more findable text/) {
>      $wanted = undef;
>    }
>    elsif ($wanted) {
>      print;
>    }
>
> }
>
> __DATA__
> junk
> junk
> junk
> findable text with a regexp
> information I care about
> more findable text
> junk
> junk
> junk

Something like this would be a little more efficient with 1 check
statment.  I've also include File handle if you have multiple files.

#!/usr/bin/perl

use strict;
use warnings;

#put your open file here
#open (IF, "< Some file") || die "Can't open $!\n";

my $regmatch = "something 123";

while (<DATA>){

print if (/$regmatch/);

}

#close (IF);

__DATA__
123
123
123
something 123


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to