dolm77
dolm77

Reputation: 111

Perl: How to split a file

I have a text file that I want to split into multiple text files using perl and output

For example:

The data starts off with:

[TABLE]

DATA........
DATA........

[/TABLE]

[PAGE]

[TABLE]

DATA........
DATA........

[/TABLE]

Desired Output:

File1.txt

DATA........
DATA........

File2.txt

DATA........
DATA........

So basically anything in between [TABLE] & [/TABLE] should be a new text file and so forth. And the naming convention for the new text files can be File1.txt, File2.txt, etc…

Please point me in the right direction.

Thanks for all your help.

 #!usr/bin/perl
 my $fi, $fi2;
 my $line;
 my $i;
 my @lines;
 my @filenameparts;
 my $filename = "file1.txt";

 open($fi, "< complex.txt");
 @lines = <$fi>;
 open ($fi2, " > $filename");

 foreach (@lines)
 {
    if (($i > 0) and $_ =~ /[TABLE]/)
 {
            @filenameparts = split("_", $filename);
            foreach (@filenameparts)
            {

             print "-----------------------------\n";
             print .$_;
             print "-----------------------------\n";               
            }
            @filenameparts[1] = substr(@filenameparts[1], 0,            @filenameparts[1].length() - 5);
            @filenameparts[1] = ($filenameparts[1] + 1);
            $filename = @filenameparts[0]."_".@filenameparts[1].".txt";
            print $filename;
            close($fi2);
            open ($fi2, " > $filename");
            $i = 0;
            print $fi2 $_;

    }
    else
    {
         print $fi2 $_;
    }
    $i++;

}  

Upvotes: 2

Views: 517

Answers (1)

Evan Carroll
Evan Carroll

Reputation: 1

How is this,

#!/usr/bin/env perl
use strict;
use warnings;
use feature ':5.10';
while ( defined( my $_ = <DATA> ) ) {

  my ( $start_tag, $end_tag );
  if ( index($_,'[TABLE]') != -1 ) {
    $start_tag = 1;
  }
  elsif ( index($_,'[/TABLE]') != -1 ) {
    $end_tag = 1;
  }

  if ( $start_tag .. $end_tag ) {
    state $fileno //= 1;
    state $fh_gen = sub {
      state $fh;
      return $fh if defined $fh;
      open ( $fh, '>', "file_$fileno.txt" ) or die $!;
      $fh;
    };

    if ( $start_tag ) {}
    elsif ( $end_tag ) {
      $fileno++;
      $fh_gen = sub {
        state $fh;
        return $fh if defined $fh;
        open ( $fh, '>', "file_$fileno.txt" ) or die $!;
        $fh;
      };
    }
    else {
      my $fh = $fh_gen->();
      print $fh $_;
    }

  }

}

__DATA__

[TABLE]

DATA........
DATA........

[/TABLE]

[PAGE]

[TABLE]

DATA........
DATA........

[/TABLE]

Upvotes: 1

Related Questions