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

如何将TXT文件中逗号分隔字符串拆分到独立列文件并生成数组

Batch脚本实现CSV列拆分与数组生成

需求说明

我是脚本语言新手,需要编写Batch脚本完成以下操作:

  • 读取包含逗号分隔字符串的TXT文件(内容如下):
James,10098,Jan
Arthur,19086,Feb
Katerina,10000,Mar
  • 将每列数据分别保存到独立的新TXT文件
  • 生成对应字符串的数组,方便在其他Batch脚本中使用

问题重现

我尝试了以下脚本,但未达到预期效果:

@echo on
setlocal ENABLEDELAYEDEXPANSION
set outputPath="C:\Users\Ben Martin\Test Scripts\"

set index=0

for /f "delims=," %%x in (Demo_MData.txt) do (
    set A[!index!] = %%x
    set /a index +=1
)

 cd %outputPath%
 Set A > %~n0_Output.txt

当前仅生成单个文件,仅包含第一列的数组:

A[0]=James
A[1]=Arthur
A[2]=Katerina

预期输出为三个独立文件:
Example1.txt

James
Arthur
Katerina

Example2.txt

10098
19086
10000

Example3.txt

Jan
Feb
Mar

解决方案脚本

@echo off
setlocal ENABLEDELAYEDEXPANSION
set "outputPath=C:\Users\Ben Martin\Test Scripts\"

:: 初始化行索引
set "rowIndex=0"

:: 逐行读取文件,拆分三列数据
for /f "tokens=1,2,3 delims=," %%a in (Demo_MData.txt) do (
    :: 将列内容追加到对应输出文件
    echo %%a >> "%outputPath%Example1.txt"
    echo %%b >> "%outputPath%Example2.txt"
    echo %%c >> "%outputPath%Example3.txt"
    
    :: 为每列创建独立数组
    set "col1[!rowIndex!]=%%a"
    set "col2[!rowIndex!]=%%b"
    set "col3[!rowIndex!]=%%c"
    
    set /a rowIndex +=1
)

:: 将数组保存到文件,供其他脚本调用
(
    set col1
    set col2
    set col3
) > "%outputPath%Arrays_Output.txt"

echo 处理完成!
endlocal

关键修改说明

  • 使用tokens=1,2,3 delims=,明确拆分每行的三个字段,分别对应%%a、%%b、%%c,解决原脚本只捕获第一列的问题
  • 通过echo %%x >> 文件路径直接将每列内容追加到对应文件,实现单列独立存储
  • 为每列创建独立数组col1、col2、col3,方便后续脚本调用
  • 将所有数组输出到Arrays_Output.txt,便于其他脚本导入使用

其他脚本调用数组示例

如果要在其他Batch脚本中使用生成的数组,可添加以下代码:

@echo off
setlocal ENABLEDELAYEDEXPANSION

:: 导入数组配置文件
for /f "delims=" %%i in (Arrays_Output.txt) do set "%%i"

:: 遍历第一列数组示例
set "index=0"
:loop
if defined col1[!index!] (
    echo 第一列第!index!行:!col1[!index!]!
    set /a index +=1
    goto loop
)
endlocal

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:45:14