我有一个文本文件,我想使用perl和输出
拆分成多个文本文件例如:
数据从以下开始:
[TABLE]
DATA........
DATA........
[/TABLE]
[PAGE]
[TABLE]
DATA........
DATA........
[/TABLE]
所需的输出:
FILE1.TXT
DATA........
DATA........
FILE2.TXT
DATA........
DATA........
基本上[TABLE]
& [/TABLE]
应该是一个新的文本文件,依此类推。新文本文件的命名约定可以是File1.txt,File2.txt等......
请指出正确的方向。
感谢您的帮助。
#!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++;
}
答案 0 :(得分:1)
这是怎么回事,
#!/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]