linux - 根据大小和出现将文件拆分为多个文件
问题描述
我有一个包含特定文本的大 txt 文件(~ 1GB)。
文件内容示例:
linux中有没有办法根据大小和同时将该文件拆分为多个文件?
因此,例如,我想将我的文件拆分为 100 MB 的文件,但每个文件必须以特定字符开头,并且它前面的文件的最后一行必须是原始文件中该字符前面的行。注意这个字符在原始文件中经常存在,所以分割文件的大小会匹配。
编辑:您可以从这里下载 txt 文件:[示例文件][2]
解决方案
正则表达式需要稍微调整,因为结果文件不完全匹配。运行它: 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
推荐阅读
- javascript - 如何将 JSON 数据提取为对象并将其更改为数组?
- modelica - 作为除数的导数在 Dymola 的初始化期间除以零
- pyspark - 如何并行化 KMeans?
- python - buildozer apk 一打开就关闭,并为我提供了很多关于我手机的信息
- javascript - Vue:单击一个时打开所有GmapInfoWindows
- awk - 如何计算每列的平均值和单独文件中的数据?
- swift - Swift 包不支持 Xib 文件吗
- perl - Perl 中的 grep “无自动生存”编译指示失败
- celery - 芹菜执行器和任务排序
- android - adb exec-out 可以用于生产吗?为什么要隐藏?