2012-02-14 72 views
1

如何在使用perl的文件行中的某些模式的基础上将很大的文件分割成许多小文件。用于文件解析的perl代码

Ex。文件:

CONECT 592 593 594               
CONECT 595 596 597               
CONECT 597 598                 
END     
CONECT 591 593 594               
CONECT 595 596 596               
CONECT 597 598                 
END 
CONECT 592 593 594               
CONECT 594 596 598               
CONECT 597 598                 
END   

我必须使许多分离文件fron单一文件。输出文件的起始行应该是'CONECT'&终止行应该是'END'。它是一个大文件(1GB)

回答

0
#!/usr/bin/perl 
use strict; 
my $file1='file_2b_read.txt'; 
my $File2='newfile_2b_created.txt'; 
open(CMD, "<$file1") or die "$!"; 
open OUTPUT, ">$File2"; 
my $cnt=1; 
while(<CMD>) { 

    print OUTPUT $_;  

    /^END/ and do { 
     #create new file 
     $cnt++; 
     close(OUTPUT); 
     $File2='newfile_2b_created'.$cnt.'.txt'; 
     open OUTPUT, ">$File2"; 
     next; 
    }; 
} 
close(CMD); 

希望这将帮助你

+0

谢谢运行,这是非常好的代码作为我的要求... – navneetcverma 2012-02-14 10:17:44

+0

关闭,虽然它会创建一个虚假的空最终文件... – zgpmax 2012-02-14 11:13:25

+0

如果是这样,然后接受答案并关闭线程 – run 2012-02-14 11:41:22

0

这是一个小算法,你可以试试。请让我知道你是否需要任何明确的代码。

while (<FD>) 
{ 
    if ($_ =~ /^END/) 
    { 
     # save buffer in new file. 
     # reset buffer. 
    } 
    # add line to buffer. 
} 
1

用更现代的Perl使用干净了一点的版本(与lexcial文件句柄3张操作数开,将呼叫open错误检查)

#!/usr/bin/perl 

use strict; 
use warnings; 

my $in_file = 'file_2b_read.txt'; 
my $out_file = 'newfile_2b_part_%06d.txt'; # Template for output filenames 
my $counter = 1; 

open my $in_fh , '<' , $in_file or die $!; 
open my $out_fh , '>' , sprintf($out_file , $counter) or die $!; 

while(<$in_fh>) { 
    print $out_fh $_; 

    if(/^END/) { 
    close($out_fh) ; 
    open $out_fh , '>' , sprintf($out_file , ++$counter) or die $!; 
    } 
} 

# cleanup afterwards 
close $out_fh ; 
close $in_fh ; 
+0

关闭,虽然它会创建一个空虚的最终文件... – zgpmax 2012-02-14 11:12:58

1

基于dgw的答案,但修改后,它不会创建一个虚假的最终文件:

#!/usr/bin/perl 

use strict; 
use warnings; 

my $in_file = 'file_2b_read.txt'; 
my $out_file_template = 'newfile_2b_part_%06d.txt'; 
my $counter = 1; 

open my $in_fh , '<' , $in_file or die $!; 
my $out_fh; 

while (<$in_fh>) { 
    if (!$out_fh) { 
     open $out_fh , '>' , sprintf($out_file_template, $counter++) or die $!; 
    } 
    print $out_fh $_; 

    if (/^END/) { 
     close($out_fh); 
     $out_fh = undef; 
    } 
} 

# cleanup afterwards 
if ($out_fh) { close($out_fh) } 
close $in_fh;