hcwzwx 发表于 2015-12-28 09:15:31

Perl根据日期分割数据文件

  Perl的优势:比C好写,比Shell高效,Linux普遍支持。



#!/usr/bin/perl -w
#    auth: lichmama@cnblogs.com
#    what: split data_file by date.
my $fullpath = $0;
my $script_name = sprintf "%s", $fullpath =~ /[^\/]*\.pl/g;
my $datafile;
my $destpath;
my $filename;
my $ARGC = scalar @ARGV;
if($ARGC<1 || $ARGC>2){
die "Usage: $script_name \n";
}else{
$datafile = $ARGV;
$filename = sprintf "%s", $datafile =~ /[^\/]*$/g;
if($ARGC == 2){
$destpath = $ARGV . "/";
}else{
$destpath = sprintf "%s", $datafile =~ /([^\/]+\/)+/g;
}
}
my %hash;
open(DATA, $datafile) or die "Error: cannot open file $datafile\n";
while(<DATA>){
my $line = $_;
my $date = substr($line, 0, 10);
if(!$hash{$date}){
open($hash{$date}, ">>$destpath$filename.$date.tmp")
or die "Error: cannot create file: $destpath$filename.$date.tmp\n";
}
print {$hash{$date}} $line;
}
close(DATA);
foreach my $fd (values(%hash)){
close($fd);
}
  
页: [1]
查看完整版本: Perl根据日期分割数据文件