FlashMX wrote:
Hi,
Hello,
I have a large file that I want to split into smaller chunks based on
a start and end text (<start>...<end>)
My script works only partially. It only saves the first occurence of
my match and then closes the script. How can I get it to keep ripping
throught the file saving into individual files.
My file I'm reading in is called test.txt
Below is just an example.
blah...blah...
blah...blah...
blah...blah...
<start>
...
<end>
blah...blah...
blah...blah...
blah...blah...
<start>
...
<end>
and so on...
Here is my script:
#!/usr/bin/perl -w
use strict;
my $written = 0;
my $index = 1;
my $filename;
if ( open( FH, 'D:\test.txt' ) )
{
$filename = sprintf( 'D:\out%d.txt', $index );
open( OUT, ">$filename" );
while ( <FH> )
{
if ( m|^<start>$| ... m|^<end>$| )
{
print OUT $_;
$written = 1;
}
else
{
if ( $written )
{
close( OUT );
$index++;
$filename = sprintf( 'C:\out%d.txt', $index );
open( OUT, ">$filename" );
$written = 0;
}
}
print "-> $_";
}
close( FH );
}
If I understand correctly then this should do what you want: (UNTESTED)
if ( open FH, '<', 'D:/test.txt' ) {
while ( <FH> ) {
my $range = /^<start>$/ .. /^<end>$/;
if ( $range == 1 ) {
my $filename = sprintf 'C:/out%d.txt', $index++;
open OUT, '>', $filename or die "Cannot open $filename: $!";
}
if ( $range ) {
print OUT;
}
else {
print "-> $_";
}
}
close FH;
}
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>