Bash 分割大的csv文件并在每个部分保留标题

Bash 分割大的csv文件并在每个部分保留标题,bash,csv,split,Bash,Csv,Split,如何分割一个大的csv文件(~100GB)并在每个部分中保留头文件 比如说 h1 h2 a aa b bb 进入 及 首先,需要将标题和内容分开: header=$(head -1 $file) data=$(tail -n +2 $file) 然后你要分割数据 echo $data | split [options...] - 在选项中,您必须指定块的大小以及结果文件名的模式。不能删除尾随的-,因为它指定split从stdin读取数据 然后可以在每个文件的顶部插入头 sed -i "

如何分割一个大的csv文件(~100GB)并在每个部分中保留头文件

比如说

h1 h2
a  aa
b  bb
进入


首先,需要将标题和内容分开:

header=$(head -1 $file)
data=$(tail -n +2 $file)
然后你要分割数据

echo $data | split [options...] -
在选项中,您必须指定块的大小以及结果文件名的模式。不能删除尾随的
-
,因为它指定
split
从stdin读取数据

然后可以在每个文件的顶部插入头

sed -i "1i$header" $splitOutputFile

显然,您应该在for循环中执行最后一部分,但其确切代码将取决于为
拆分操作选择的前缀。

我发现以前的解决方案无法在我的脚本所针对的mac系统上正常工作(为什么是苹果?为什么?)我最终得到了一个printf选项,作为概念证明,它的效果非常好。我将通过将临时文件放入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

您可以从下载免费软件CsvSplitter。它是一个来自网站的zip文件,包含一个简单的可移植.exe文件和一个.txt文件,需要与可执行文件一起工作,只需提取某个目录中的内容,即可开始工作:

它可以分割文件,如图所示

一切都是不言自明的,但更多的细节可以找到

我们怎么能用这样一个小例子知道“每个部分”是什么?这太宽泛了。提供一个与您尝试的内容相结合的示例。
sed -i "1i$header" $splitOutputFile
#!/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