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

如何用批处理脚本按固定长度拆分单行海量记录?

批处理实现按固定字节拆分单行文本

需求说明

将每行独立的文本记录按固定字节长度拆分(示例为10字符/字节,实际要求800字节),拆分后的每段单独占一行。

批处理脚本(适用于ANSI编码文件)

如果你的文本文件使用ANSI编码(每个字符占1字节),可以直接使用以下批处理脚本:

@echo off
setlocal enabledelayedexpansion

:: 配置参数:设置拆分的字节长度、输入输出文件名
set "split_bytes=800"
set "input_file=input.txt"
set "output_file=output.txt"

:: 检查输入文件是否存在
if not exist "%input_file%" (
    echo 错误:输入文件 %input_file% 不存在!
    pause
    exit /b 1
)

:: 清空输出文件(如果存在)
del "%output_file%" 2>nul

:: 逐行处理输入文件
for /f "usebackq delims=" %%a in ("%input_file%") do (
    set "current_line=%%a"
    :split_loop
    :: 判断是否还有剩余内容
    if "!current_line!"=="" goto :next_line
    :: 截取前%split_bytes%字节的内容(ANSI编码下字符=字节)
    set "segment=!current_line:~0,%split_bytes%!"
    :: 将分段写入输出文件
    echo !segment!>>"%output_file%"
    :: 移除已处理的部分
    set "current_line=!current_line:~%split_bytes%!"
    goto split_loop
    :next_line
)

echo 拆分完成!结果已保存到 %output_file%
pause

使用说明

  1. 修改split_bytes的值为你需要的800
  2. 替换input_file和output_file为实际的文件名
  3. 保存为.bat文件,和输入文件放在同一目录运行即可

注意事项

  • 批处理脚本仅在ANSI编码下能保证按字节拆分,因为ANSI编码中每个字符对应1字节。如果是UTF-8等多字节编码,批处理的字符截取会破坏多字节字符(比如中文、特殊符号),此时建议使用PowerShell脚本。

PowerShell脚本(支持任意编码,严格按字节拆分)

如果需要处理UTF-8等多字节编码文件,确保严格按800字节拆分且不破坏字符,使用以下PowerShell脚本:

# 配置参数
$splitByteLength = 800
$inputFilePath = "input.txt"
$outputFilePath = "output.txt"
# 根据文件实际编码修改,可选值:ASCII, UTF8, Unicode, Default(ANSI)
$fileEncoding = [System.Text.Encoding]::UTF8

# 读取文件为字节数组
$fileBytes = [System.IO.File]::ReadAllBytes($inputFilePath)
$outputStream = [System.IO.File]::Create($outputFilePath)

try {
    $totalBytes = $fileBytes.Length
    $currentOffset = 0
    while ($currentOffset -lt $totalBytes) {
        # 计算当前块的字节数(剩余不足800则取剩余全部)
        $chunkSize = [Math]::Min($splitByteLength, $totalBytes - $currentOffset)
        # 写入当前字节块
        $outputStream.Write($fileBytes, $currentOffset, $chunkSize)
        # 写入换行符(按指定编码生成)
        $newLineBytes = $fileEncoding.GetBytes("`r`n")
        $outputStream.Write($newLineBytes, 0, $newLineBytes.Length)
        # 更新偏移量
        $currentOffset += $chunkSize
    }
}
finally {
    # 关闭输出流
    $outputStream.Close()
}

Write-Host "拆分完成!结果已保存到 $outputFilePath"

使用说明

  1. 修改splitByteLength为800,设置正确的文件路径和编码
  2. 保存为.ps1文件,右键选择“使用PowerShell运行”即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:47:28