How to split a string by spaces in a Windows batch file?

Three possible solutions to iterate through the words of the string:

Version 1:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
for %%a in (%s%) do echo %%a

Version 2:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
set t=%s%
:loop
for /f "tokens=1*" %%a in ("%t%") do (
   echo %%a
   set t=%%b
   )
if defined t goto :loop

Version 3:

@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
call :sub1 %s%
exit /b
:sub1
if "%1"=="" exit /b
echo %1
shift
goto :sub1

Version 1 does not work when the string contains wildcard characters like ‘*’ or ‘?’.

Versions 1 and 3 treat characters like ‘=’, ‘;’ or ‘,’ as word separators. These characters have the same effect as the space character.

Leave a Comment