The FOR loop only outputs the first item of the list and I'm trying to go over the whole list.
@ECHO OFF
set list=this,is,a,list
FOR /f "tokens=1* delims=," %%a IN ("%list%") DO echo %%a
pause
Python String split() Method Python split() method splits the string into a comma separated list. It separates string based on the separator delimiter. This method takes two parameters and both are optional. It is described below.
To avoid confusion with the batch parameters, %0 through %9 , you can use any character for variable except the numerals 0 through 9. For simple batch files, a single character such as %%f will work. You can use multiple values for variable in complex batch files to distinguish different replaceable variables.
The FOR /F
command split a line in several tokens, that must be referenced individually via separate letters:
@ECHO OFF
set list=this,is,a,list
FOR /f "tokens=1-4 delims=," %%a IN ("%list%") DO (
echo %%a
echo %%b
echo %%c
echo %%d
)
pause
The plain FOR
command process a series of elements separated by space, or by the standard Batch file delimiters: comma, semicolon or equal-sign:
@ECHO OFF
set list=this,is,a,list
FOR %%a IN (%list%) DO echo %%a
pause
Open a command prompt window, run for /?
and read the output help.
With tokens=1*
the first string delimited by 1 or more commas (,,,
is like 1 comma!) is assigned to loop variable a
which is here the word this
. And the rest of the string being is,a,list
is assigned to loop variable b
(next after a
in ASCII table) which is not referenced at all in provided code snippet.
Here is a batch code demonstrating how to process each substring of a comma separated string:
@echo off
set "List=this,is,a,list"
set ItemCount=0
:NextItem
if "%List%" == "" pause & goto :EOF
set /A ItemCount+=1
for /F "tokens=1* delims=," %%a in ("%List%") do (
echo Item %ItemCount% is: %%a
set "List=%%b"
)
goto NextItem
The output is:
Item 1 is: this
Item 2 is: is
Item 3 is: a
Item 4 is: list
There are of course also other solutions possible. This is just an example.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
goto /?
if /?
pause /?
set /?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With