Perl - 如何将文件拆分为较小的文件

时间:2013-05-14 07:28:17

标签: perl

我需要建议如何制作一个能够使用数字线将文件拆分成较小文件的perl程序。

例如:

perl split.pl --file="data.txt" --numberLine=2

输入

data.txt中:

line1
line2
line3
line4

输出

DATA1.TXT

line1
line2

data2.txt

line3
line4

perl split.pl --file="data.txt" --numberLine=1

DATA1.TXT

line1

data2.txt

line2

data3.txt

line3

data4.txt

line4

或     perl split.pl --file =“data.txt”--numberLine = 3

DATA1.TXT

line1
line2
line3

data2.txt

line4

3 个答案:

答案 0 :(得分:5)

分裂:

system("split -l 2 $file");

答案 1 :(得分:1)

#!/usr/bin/perl
#

use strict;
use warnings;
use Getopt::Long;
use File::Basename;
my ($length, $file);

my $res= GetOptions ("numberLine=i" => \$length,
                      "file=s" => \$file);

my ($name,$path,$suffix) = fileparse($file,("\.txt","\.dat"));

open(my $fh,$file) || die "$file $!";

my $lc=0;
my $outfh=undef;
while(<$fh>) {
    if (($lc % $length) == 0) {
            my $n=int($lc/$length)+1;
            open($outfh,">$name$n.txt") || warn "$name$n.txt $!";
            }
    $lc++;
    print $outfh $_;
    }

或者,这里是如何将其作为一个班轮。您只需在脚本行中自行设置“numberLines”,并将文件名作为args

提供
perl -n -e 'print; unless (($.-1)%2){$n++;open(F,">data$n.txt")} print F $_' data.txt

答案 2 :(得分:0)

 sed -e '1,2wdata1.txt' -e '3,$wdata2.txt' data.txt