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:


VECT
1 1 1
2 2 2
3 3 3

VECT
4 4 4
5 5 5
6 6 6

etc...

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(); } }

In reply to splitting a large text file and output by research_guy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.