You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell将大型NDJSON文件按行数均等拆分?

使用PowerShell拆分大型NDJSON文件为均等行数的多个文件

针对将440万行的NDJSON文件拆分为4个各110万行文件的需求,可通过以下PowerShell脚本实现,该方法采用逐行读取模式,避免一次性加载大文件占用过多内存:

# 配置参数
$sourceFile = "C:\path\to\your\source.ndjson"  # 替换为你的源文件路径
$linesPerFile = 1100000
$outputPrefix = "split_part_"
$outputDir = "C:\path\to\output\folder\"  # 替换为输出目录路径

# 初始化计数器与文件索引
$lineCounter = 0
$fileNum = 1
$currentOutput = Join-Path -Path $outputDir -ChildPath "$outputPrefix$fileNum.ndjson"

# 逐行处理并写入
foreach ($line in [System.IO.File]::ReadLines($sourceFile)) {
    Add-Content -Path $currentOutput -Value $line -Encoding utf8
    $lineCounter++

    # 达到指定行数时切换输出文件
    if ($lineCounter -eq $linesPerFile) {
        $fileNum++
        $currentOutput = Join-Path -Path $outputDir -ChildPath "$outputPrefix$fileNum.ndjson"
        $lineCounter = 0
    }
}

关键说明

  • 内存优化:使用[System.IO.File]::ReadLines()逐行读取,不会将整个大文件加载到内存,适合处理百MB级文件。
  • 编码一致性:指定-Encoding utf8保证输出文件编码与源文件匹配,避免乱码。
  • 可扩展性:修改$linesPerFile可调整单文件行数,修改$outputPrefix可自定义输出文件名前缀。

注意事项

  1. 确保输出目录已存在,若不存在可提前执行New-Item -Path $outputDir -ItemType Directory -Force创建。
  2. 若源文件总行数无法被拆分数量整除,最后一个文件行数会略少于指定值(本次需求为刚好整除,无需额外处理)。

内容的提问来源于stack exchange,提问作者Naveen Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:20:28