Perl按行分割文件


Perl按行分割文件

將一個文件按照行數,均等的分割成多個小文件,例如,一個550行的文件,分割為每個文件有100行,則將分割為6個小文件

運行結果


參考代碼(split_file.pl)

#!/usr/bin/perl
#usage way: split_file.pl test

open(FILE,$ARGV[0]) or die ("Error: cannot open file $ARGV[0].\n");
@lst_line = <FILE>;

my $dir_num = &splitfile(@lst_line);


#print "$dir_num\n";

exit;
################################################################


################################################################
sub splitfile{
    my (@input_line) = @_;
    
    my $everyfule_num = 80;   #Set partition lines
    my $line_num = @input_line;
    my $split_num  = $line_num/$everyfule_num;
    
    unlink "temp_lst";
    open(TEMPA, ">> temp_lst") || die ("Could not open file temp_lst! \n");

    my $sq_num = 0;
    foreach $line (@input_line){
        $line_index ++;

        printf TEMPA ("$line");

        if($line_index%$everyfule_num == 0){
            $sq_num = $line_index/$everyfule_num;
            my $lst_name = "test_"."lst_".$sq_num;
            rename "temp_lst",  "$lst_name";
            close TEMPA;

            unlink "temp_lst";
            open(TEMPA, ">> temp_lst") || die ("Could not open file temp_lst! \n");
        }
    }

    rename "temp_lst",  "test_"."lst_".($sq_num+1);
    close TEMPA;

    return $sq_num+1;
} #end of splitfile


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM