根据大小将非常大的CSV文件拆分为较小的文件

xvw2m8pv  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(118)

我有一个133 GB的CSV文件,在我的本地系统中有标题。我想把这个文件分成5部分,每个文件都应该包含标题。
我试过通过git bash命令split -b size largefile.csv来实现
但这现在工作正常

2admgd59

2admgd591#

我不认为您可以使用常见的Unix行处理工具来完成CSV的拆分,至少不容易。
我推荐一个支持CSV的工具,它有一些功能,可以让你指定你想要多少个文件或每个文件多少行:

  • 米勒的split命令允许您指定每个文件的最大行数,或者设置文件的数量(但是RoundRobin,参见示例)
  • GoCSV的split命令允许您指定每个文件的最大行数

我喜欢GoCSV,所以我将展示如何使用它的split命令来实现我认为你想要的:

#!/bin/bash

fname=input.csv

# Get number of rows in CSV
nrows=$(gocsv nrow $fname) || exit 1

# Get desired number of files
printf "%s" "Number of split CSVs: "
read nfiles

# Calculate rows per file
nRowsPerFile=$(( (nrows / nfiles) + 1 ))
echo "Will split $fname with $nrows rows into $nfiles files, each with a max of $nRowsPerFile rows"

# Remove any previous splits, split to files starting with name "split"
rm split-*.csv
gocsv split -filename-base split -max-rows $nRowsPerFile $fname || exit 1

# Check work
echo ""
ls split-*.csv | while read CSV; do 
    nrows=$(gocsv nrow "$CSV") || exit 1
    echo "$CSV $nrows"
done

字符串
我用随机数据生成了一个CSV,它有1_234_567行(大约46MB)。当我运行以下输入时,我得到:

  • 1个分割文件:
Number of split CSVs: 1
Will split input.csv with 1234567 rows into 1 files, each with a max of 1234568 rows
split-1.csv 1234567

  • 3个分割文件:
Number of split CSVs: 3
Will split input.csv with 1234567 rows into 3 files, each with a max of 411523 rows
split-1.csv 411523
split-2.csv 411523
split-3.csv 411521

  • 5个分割文件:
Number of split CSVs: 5
Will split input.csv with 1234567 rows into 5 files, each with a max of 246914 rows
split-1.csv 246914
split-2.csv 246914
split-3.csv 246914
split-4.csv 246914
split-5.csv 246911

相关问题