如何在不截断记录的情况下将大型文本文件拆分为大小均匀的文件?

Man*_*Man 3 unix perl

我有一个大文本文件(大约10 GB),其中包含多个故事.每个故事都以标记开头$$.以下是该文件的示例:

$$
AA This is story 1
BB 345

$$

AA This is story 2
BB 456
Run Code Online (Sandbox Code Playgroud)

我想将此文件拆分为大约250 MB的大小.但是这些故事都不应该分成两个不同的文件.

任何人都可以帮助我使用Unix或Perl代码吗?

yst*_*sth 5

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;
}
Run Code Online (Sandbox Code Playgroud)