ExperimentsWithPerl has asked for the wisdom of the Perl Monks concerning the following question:
Hi
I am trying to parse a text file so print subsection of a file based on how many times the start and end strings are present in the file.
Now my sample.txt file is
1st line to ignore
2nd line to ignore
print from this line 1
lets print the following line too 1
Okay lets close it now 1
closing at this line 1
this was fine
but now is the problem
2nd line to ignore
print from this line as well 2
lets print the following line too 2
Okay lets close it too now 2
closing at this line 2
No I dont want to print this line
bye
I want my output to be
print from this line 1
lets print the following line too 1
Okay lets close it now 1
closing at this line 1
print from this line as well 2
lets print the following line too 2
Okay lets close it too now 2
closing at this line 2
But not able to achive the same.Tried two piece of
codes:-
and#!/usr/bin/perl use strict; use warnings; undef $/; open (FILE, '<', 'sample.txt') or die "Could not open sample.txt: +$!"; my $file = <FILE>; my ($printline) = $file =~ m/.*?(print from.*?closing).*/sg; print $printline; close (FILE) or die "Could not close sample.txt: $!";
. Kindly help.open (FILE, '<', 'sample.txt') or die "Could not open sample.txt: +$!"; open (FILE1, '>', 'output.txt') or die "Could not open output.txt: + $!"; my @file = <FILE>; # Whole file here now... my $sizeconf = scalar @file; #print $sizeconf; my $j = 0; #print $file[2]; for (my $i ; $i < $sizeconf ; $i++) { if ($file[$i] =~ /print from/){ #print $i; print $file[$i] if ($file[$i] !~ /closing/); my $sum = $i+1; for ($sum; $i < $sizeconf ; $i++){ #$sum = $i+1; print "$file[$i+1]"; #$i++ ; if ($file[$i] =~ /closing/ ){ print $file[$i]; break; } } } } close (FILE) or die "Could not close sample.txt: $!"; close (FILE1) or die "Could not close output.txt: $!";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Parsing a file to print multiple times
by Anonymous Monk on Sep 26, 2015 at 07:59 UTC | |
by ExperimentsWithPerl (Acolyte) on Sep 26, 2015 at 08:05 UTC | |
by Anonymous Monk on Sep 26, 2015 at 08:14 UTC | |
by ExperimentsWithPerl (Acolyte) on Sep 26, 2015 at 10:21 UTC | |
by ExperimentsWithPerl (Acolyte) on Sep 29, 2015 at 11:31 UTC |