如何使用PowerShell为无换行CSV按指定字段数添加换行分隔符
PowerShell 批量拆分单行长CSV为多行固定字段数记录方案
核心实现脚本
你可以直接使用以下可自定义参数的PowerShell脚本完成处理,普通大小文件可直接使用:
# 配置参数,根据你的实际需求修改 $inputPath = "C:\path\to\your\input.csv" # 源文件完整路径 $outputPath = "C:\path\to\your\output.csv" # 输出文件完整路径 $fieldsPerLine = 3 # 每行需要包含的字段数,可自定义调整 $delimiter = "," # 字段分隔符,默认逗号,若为其他符号可直接修改 # 读取源文件整行内容,按分隔符拆分所有字段 $allFields = (Get-Content -Path $inputPath -Raw) -split $delimiter | ForEach-Object { $_.Trim() } # 按固定数量拆分字段并写入输出文件 for ($i = 0; $i -lt $allFields.Count; $i += $fieldsPerLine) { $endIndex = [Math]::Min($i + $fieldsPerLine - 1, $allFields.Count - 1) $lineContent = $allFields[$i..$endIndex] -join $delimiter Add-Content -Path $outputPath -Value $lineContent }
大文件专用版本
如果你的CSV文件体积在GB级,可使用以下流式处理版本,内存占用可控不会出现卡死问题:
$inputPath = "C:\path\to\your\input.csv" $outputPath = "C:\path\to\your\output.csv" $fieldsPerLine = 3 $delimiter = "," $fieldBuffer = @() $streamReader = [System.IO.StreamReader]::new($inputPath) while (-not $streamReader.EndOfStream) { $rawContent = $streamReader.ReadLine() $splitFields = $rawContent -split $delimiter | ForEach-Object { $_.Trim() } $fieldBuffer += $splitFields while ($fieldBuffer.Count -ge $fieldsPerLine) { $outputLine = $fieldBuffer[0..($fieldsPerLine - 1)] -join $delimiter Add-Content -Path $outputPath -Value $outputLine $fieldBuffer = $fieldBuffer[$fieldsPerLine..($fieldBuffer.Count - 1)] } } $streamReader.Close() # 处理剩余不足一行的字段 if ($fieldBuffer.Count -gt 0) { $outputLine = $fieldBuffer -join $delimiter Add-Content -Path $outputPath -Value $outputLine }
结果验证
脚本运行完成后,可通过以下命令查看前10行确认格式是否符合预期:
Get-Content -Path $outputPath -Head 10
确认无误后即可直接导入Excel或其他工具处理。
内容的提问来源于stack exchange,提问作者gallis
相关产品推荐
相关产品推荐

