2016-05-23 58 views
2

如何分割CSV文件较大(〜100GB)并保存在每个部分的标题?拆分大csv文件,并保持头在每个部分

例如

h1 h2 
a aa 
b bb 

h1 h2 
a aa 

h1 h2 
b bb 
+1

我们怎么才能知道什么是“每个部分”与这样一个微小的例子? – fedorqui

+1

这太宽泛了。提供[mcve]以及您尝试的内容。 – fedorqui

回答

4

首先,你需要的标题和内容分离:

header=$(head -1 $file) 
data=$(tail -n +2 $file) 

然后你要拆分的数据

echo $data | split [options...] - 

在你指定块的大小和生成的文件名模式的选项。尾部-不能删除,因为它指定split从标准输入读取数据。

然后你就可以在每个文件

sed -i "1i$header" $splitOutputFile 

很显然你应该做的最后一部分在for循环的顶端插入头,但其确切的代码将取决于选择的split操作的前缀。

1

,我发现这个以往任何解决方案,不,我的剧本是针对(苹果为什么?为什么?)我终于结束了与制定出相当不错的概念证明一个printf选项Mac系统正常工作。我将通过将临时文件放入ramdisk等来提高性能,以便提高性能,因为它会将一堆磁盘放在磁盘上,并且可能会很慢。

#!/bin/sh 

# Pass a file in as the first argument on the command line (note, not secure) 
file=$1 

# Get the header file out 
header=$(head -1 $file) 

# Separate the data from the header 
tail -n +2 $file > output.data 

# Split the data into 1000 lines per file (change as you wish) 
split -l 1000 output.data output 

# Append the header back into each file from split 
for part in `ls -1 output*` 
do 
    printf "%s\n%s" "$header" "`cat $part`" > $part 
done