我有一个大文本文件(大约10 GB),其中包含多个故事.每个故事都以标记$$开头.以下是该文件的示例:
$$ AA This is story 1 BB 345 $$ AA This is story 2 BB 456
我想将此文件拆分为大约250 MB的大小.但是这些故事都不应该分成两个不同的文件.
任何人都可以帮助我使用Unix或Perl代码吗?
解决方法
use strict; use warnings; use autodie; $/ = "\$\$\n"; my $targetsize = 250*1024*1024; my $fileprefix = 'chunk'; my $outfile = 0; my $outfh; my $outsize = 0; while (my $story = <>) { chomp($story); next unless $story; # disregard initial empty chunk $story = "$/$story"; # no file open yet,or this story takes us farther from the target size if ( ! $outfile || abs($outsize - $targetsize) < abs($outsize + length($story) - $targetsize) ) { ++$outfile; open $outfh,'>',"$fileprefix$outfile"; $outsize = 0; } $outsize += length($story); print $outfh $story; }