split text file?

P

pc

hi everyone,

I have a report that has three headings throughout the report. I want
to split the report into three text files called section 1, section 2,
section 3. is there a simple way of accomplishing this in perl?

tia

eddiec :)
 
U

usenet

pc said:
I want to split the report into three text files called section 1, section 2,
section 3. is there a simple way of accomplishing this in perl?

Sure, piece-o-cake, especially with a little help from IO::All. This
assumes, of course, that your "heading" is distinctive and won't occur
within the main text. You didn't provide a sample of your headings or
data, so I made something up based on comic-strip characters, which I
read from __DATA__ for usenet convenience; adapt per your requirements:

#!/usr/bin/perl
use strict; use warnings;

use IO::All;

my $io; # [ IO::All handle ]
while ( <DATA> ) {
$io = io("/tmp/$1.txt") if /== (.*) ==/;
$io -> print($_) if $io;
}

__DATA__
== PEANUTS ==
Charlie Brown
Lucy

== DILBERT ==
Dilbert
Wally
Pointy-Haired Boss

== GARFIELD ==
Odie
Jon
 
T

Tad McClellan

pc said:
I have a report that has three headings throughout the report. I want
to split the report into three text files called section 1, section 2,
section 3. is there a simple way of accomplishing this in perl?


Yes.
 
X

Xicheng

you can do it on the command line:
perl -ne 'if(/=heading pattern=/) {$n++;open FH,">","section $n"}
print FH;END{close FH}' file.txt
or if you don't need the heading into your splited files:
perl -ne 'if(/=heading pattern=/) {$n++;open FH,">","section
$n";next} print FH;END{close FH}' file.txt

At least for some small-sized files, the "END{close FH}" statement can
often be neglected.
Good luck,
Xicheng
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top