我有这个perl脚本(下面),它通过每个文件中的行数将1个数据文件拆分成多个。我正在尝试调整此脚本以将第一个文件(标题行)的第一行写入每个拆分文件的顶部。这样做的最佳方式是什么?
use strict;
use warnings;
my $source = shift or &usage();
my $lines_per_file = shift or &usage();
my $filename = shift or &usage();
my $target = shift or &usage();
my $filenum = 2;
my $dir = "${target}";
chdir($dir) or die "Failed to cd to $dir: $!";
$filename =~ s{\.[^.]+$}{};
open (my $FH, "<$source") or die "Could not open source file. $!";
open (my $OUT, ">${filename}_1.csv") or die "Could not open destination file. $!";
print "Writing file: ${filename}_1.csv\n";
my $i = 0;
while (<$FH>) {
print $OUT $_;
$i++;
if ($i % $lines_per_file == 0) {
close($OUT);
my $FHNEW = ($filenum);
open ($OUT, ">${filename}_${FHNEW}.csv") or die "Could not open destination file. $!";
print "Writing file: ${filename}_${filenum}.csv\n";
$filenum++;
}
}
sub usage() {
print <<EOF;
PROGRAM NAME: Split .csv file
DESCRIPTION:
Takes a file and creates many small files out of the large file.
EXAMPLE USAGE: splitfile.pl filename.csv 300000 filename /dir/
PARAMETERS:
1. Source File: File name of the source file to partition.
2. Maximum number of lines per file: The number of lines per file.
3. Filename without the extension
4. Target location of split files ending with /
EOF
exit;
}
答案 0 :(得分:0)
@content = <$FH>;
print $content[0];
顺便说一下,有很多不同的方法可以做到这一点。你也可以用命令打印。比如
foreach my $file(glob "$dir.*")
{
print `head -n 1 $file`;
}