批处理文件字符串生成器

Batch-file string builder

我想创建一个字符串生成器,以使用批处理文件组合 .txt 文件的行内容,以便稍后导入它 (CSV)。

源文件包含重复自身的信息行,例如 3 次。像这样:

Info1 a
Info2 b
Info3 c
Info1 aa
Info2 DD
Info3 ff

新的目标文件应如下所示:

Info1 a; Info2 b; Info3 c
Info1 aa; Info2 dd; Info3 ff

这是我的开始代码:

set OutFile=D:\outfile.txt 
if exist %OutFile% del /q %OutFile%
set counter=0;
for /F "tokens=*" %%y in (D:\list.txt) do (
if %counter% == 0 do (
set string=%%y
)
if %counter% == 2 do (
 echo %string%>>%OutFile%
)

if %counter% != 0  && %counter% != 2 do (
set string=%string% and ";" and %%y
)
)

感谢您的帮助!

我稍微修改了你的源文件:

  • 不要删除存在的输出文件,而是始终创建一个空文件(copy 命令)
  • _RepeatCount 保存模式重复时的行数(如果输入文件格式改变,请更改它)
  • 我正在使用 delayed expansion
  • 算法很简单:我遍历输入文件的每一行,并将其添加到保存已读取行的变量中;每次我读 _RepeatCount 行时,我都会将变量转储到输出文件中并重置它。最后一个 if 子句 if 用于处理输入文件的行数不是 _RepeatCount 的倍数的情况,它们也将被转储到输出文件中。

代码如下:

@echo off
setlocal enableextensions, enabledelayedexpansion

set OutFile=D:\outfile.txt 
copy NUL %OutFile%

set InFile=D:\list.txt

set _RepeatCount=3
set _Index=0

for /F "tokens=*" %%y in (%InFile%) do (
    set /A _Index=_Index + 1
    if !_Index! equ %_RepeatCount% (
        set _Lines=!_Lines!%%y
        set _Index=0
        echo !_Lines! >> %OutFile%
        set _Lines=
    ) else (
        set _Lines=!_Lines!%%y; 
    )
)
if "%_Lines%" neq "" (
    echo %_Lines% >> %OutFile%
)