首页 > 解决方案 > 根据大小和出现将文件拆分为多个文件

问题描述

我有一个包含特定文本的大 txt 文件(~ 1GB)。

文件内容示例:

linux中有没有办法根据大小和同时将该文件拆分为多个文件?

因此,例如,我想将我的文件拆分为 100 MB 的文件,但每个文件必须以特定字符开头,并且它前面的文件的最后一行必须是原始文件中该字符前面的行。注意这个字符在原始文件中经常存在,所以分割文件的大小会匹配。

编辑:您可以从这里下载 txt 文件:[示例文件][2]

标签: linuxfilesplit

解决方案


正则表达式需要稍微调整,因为结果文件不完全匹配。运行它: perl scriptname.pl < sample.txt 你会得到块文件。

#!/usr/bin/perl -w

use strict;
use IO::File;


my $all = join('', (<STDIN>));

my (@pieces) = ($all =~ m%([IZO]\(.*?\)\{.*?\r\n\}\r\n)%gsx);

my $n = 1;
my $FH;
foreach my $P (@pieces) {
   if ($P =~ m%^I%) {
      undef $FH;
      $FH = IO::File->new(sprintf("> chunk%d", $n));
      $n++;
   }
   print $FH $P;
}

更少的内存消耗:

#!/usr/bin/env python

import sys

def split(filename, size=100, outputPrefix="xxx"):
    with open(filename) as I:
        n = 0
        FNM = "{}{}.txt"
        O = open(FNM.format(outputPrefix, n), "w")
        toWrite = size*1024*1024
        for line in I:
            toWrite -= len(line)
            if line[0] == 'I' and toWrite < 0:
                O.close()
                toWrite = size*1024*1024
                n += 1
                O = open(FNM.format(outputPrefix, n), "w")
            O.write(line)
        O.close()

if __name__ == "__main__":
    split(sys.argv[1])

使用:python scriptname.py sample.txt 所有连接的文件都等于 sample.txt


推荐阅读