簡單拆分文本指令碼 今天被老師喊過來幫個小忙,有個檔案太大了,把它分了。 在這裡留個備份吧。 01#!/usr/bin/perl -w02use strict;03use warnings;04# 拆分文字檔05# 可以建個檔案夾06# 目前是 csv07 08my $csv = 'xxx.csv';09print "File read from is '$csv'.\n";10my $in_fh = read_text($csv);11 12# 檔案數目13my $num_of_files = 15;14 15# 行數16my $total_lines = 12465682; # 總行數17# 各文本大致行數18my $lines = int($total_lines / $num_of_files);19 20my $count = 0;21my $n = 1;22my $out_file = "xxx_$n.csv";23print "Create $out_file ...\n";24my $w_fh = write_text($out_file);25 26while (<$in_fh>) {27 if ($n < $num_of_files and $count == $lines) {28 $n++;29 $count = 0;30 close $w_fh;31 $out_file = "xxx_$n.csv";32 print "Create $out_file ...\n";33 $w_fh = write_text($out_file);34 }35 print $w_fh $_;36 $count++;37}38close $w_fh;39close $in_fh;40 41print "Done!\n";42exit;43 44#====================================================45# subroutions46 47# 讀取文字檔48sub read_text {49 my $filename = shift;50 my $fh;51 open $fh, '<', $filename or die "Cannot open file '$filename': $!";52 return $fh;53}54 55# 寫文字檔56sub write_text {57 my $filename = shift;58 my $fh;59 open $fh, '>', $filename or die "Cannot open file '$filename': $!";60 return $fh;61}