@echo off
cd /d "%~dp0"
setlocal enabledelayedexpansion
For /F tokens^=* %%i in ('type "example.txt"
')do set /a "_cnt+=1+0" && call set "_var!_cnt!=%%~i"
For /L %%L in (1 1 !_cnt!)do For /F tokens^=*usebackq %%i in (
`echo[!_var%%~L!`)do if not defined _var_ (set "_var_=_var%%L=!_var%%~L!"
) else set "_var_=!_var_!, _var%%~L=!_var%%~L!"
echo\!_var_!>example2.txt && set /p _var=<example2.txt
echo\!_var! && for /L %%L in (1 1 !_cnt!)do echo\!_var%%~L!
endlocal && goto :EOF
_var1=data1, _var2=data2, _var3=data3 // - From echo\!_var!
data1 // |
data2 // | From For /L loop
data3 // |
1. Implement a counter inside a For /F loop taking line by line from your file:
For /F tokens^=* %%i in ('type "example.txt"
')do set /a "_cnt+=1+0" && ...
2. Each line will be saved isolated in the variable _var + counter
... && call set "_var!_cnt!=%%~i"
3. Implement a For /L loop starting at 1 and incrementing to the value defined in the counter == ! _cnt!
For /L %%L in (1 1 !_cnt!)do ...
4. Concatenate the string _var with the variable in loop %%L, in order to recover the value of each line saved in _var%%L to use it in an additional For /F loop
... do For /F tokens^=*usebackq %%i in (
`echo[!_var%%~L!`)do
5. Use a conditional if, where the _var_ variable has already been defined, define it in order to add more strings in the variable or, just define it with the value of the first line (var%%L == var1 == data1)
... do if not defined _var_ (set "_var_=_var%%L=!_var%%~L!"
) else set "_var_=!_var_!, _var%%~L=!_var%%~L!"
6. If for a reason you need this variable defined by set /p, echo the variable _var redirected to another file, and use it
echo\!_var_!>example2.txt && set /p _var=!<example2.txt
Obs.: 1 Remember item 4.: Concatenate the string _var with the variable in loop %%L, in order to recover the value of each line saved in _var%%L to use it in an additional For /F loop
echo\!_var! && for /L %%L in (1 1 !_cnt!)do echo\!_var%%~L!
Ob.: 2 Both the variable _var_ and _var, have the same content/strings/lines saved in them
echo\!_var!
echo\!_var_!