research_guy has asked for the wisdom of the Perl Monks concerning the following question:
I have text file that is around 1000 files long and I need to split it every 12 lines or at a header and repeatedly and then output each section to its own .txt file.
The txt file looks like:
There are 12 lines for each section of text that I need to split or I need to split them based on the name of the repeated header. After they are split, I need them to be inputted into individual txt files that are given a unique number for each one (i.e. file1, file2, file3, ... etc). Also, I need the header included in each of the created text files and I would prefer to keep the original file intact and not alter it. I've tried reading it in and setting up for loops and such, but I cannot get anything that works. Your help is much appreciated!
Here is some of the code that I have tried. This one splits the up the file and puts into 3 files what I want to put in just one file so I have 3,000 files instead of 1,000 files. Also, the program didn't put in a file for the last section of information. Any ideas?
#!/usr/bin/perl use strict; use warnings; my $infile = 'roegen6.vect'; my $count = 1; my $outfile = "$infile-section_$count.vect"; my @arr; sub create_file { open(OUT,">$outfile") or die "Error with outfile: $!\n"; print OUT @arr; close(OUT); @arr=(); $count++; $outfile="$infile-section_$count.vect"; } open(IN,$infile) or die "Error with infile $infile: $!\n"; my @data=<IN>; close(IN); foreach my $line (@data) { chomp($line); if ($line =~ /VECT/) { push (@arr, "$line\n"); next; } elsif ($line != /\s/) { push (@arr, "$line\n"); next; } else { push (@arr, "$line\n"); create_file(); } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: splitting a large text file and output
by kennethk (Abbot) on Jun 10, 2011 at 14:57 UTC | |
by Gulliver (Monk) on Jun 10, 2011 at 16:35 UTC | |
|
Re: splitting a large text file and output
by davido (Cardinal) on Jun 10, 2011 at 16:33 UTC | |
|
Re: splitting a large text file and output
by johngg (Canon) on Jun 10, 2011 at 17:56 UTC | |
by 7stud (Deacon) on Jun 10, 2011 at 18:10 UTC | |
|
Re: splitting a large text file and output
by 7stud (Deacon) on Jun 10, 2011 at 18:00 UTC | |
by johngg (Canon) on Jun 10, 2011 at 22:22 UTC | |
|
Re: splitting a large text file and output
by Khen1950fx (Canon) on Jun 10, 2011 at 17:05 UTC | |
|
Re: splitting a large text file and output
by Marshall (Canon) on Jun 11, 2011 at 15:09 UTC |