How to split a string by spaces in a Windows batch file?
Suppose I have a string "AAA BBB CCC DDD EEE FFF".
How can I split the string and retrieve the nth substring, in a batch file?
The equivalent in C# would be
"AAA BBB CCC DDD EEE FFF".Split()[n]
HELP FOR and see the examples
or quick try this
for /F %%a in ("AAA BBB CCC DDD EEE FFF") do echo %%c
Three possible solutions to iterate through the words of the string:
@echo off & setlocal set s=AAA BBB CCC DDD EEE FFF for %%a in (%s%) do echo %%a
@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
@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.
Read more... Read less...
This is the only code that worked for me:
for /f "tokens=4" %%G IN ("aaa bbb ccc ddd eee fff") DO echo %%G
The following code will split a string with an arbitrary number of substrings:
@echo off setlocal ENABLEDELAYEDEXPANSION REM Set a string with an arbitrary number of substrings separated by semi colons set teststring=The;rain;in;spain REM Do something with each substring :stringLOOP REM Stop when the string is empty if "!teststring!" EQU "" goto END for /f "delims=;" %%a in ("!teststring!") do set substring=%%a REM Do something with the substring - REM we just echo it for the purposes of demo echo !substring! REM Now strip off the leading substring :striploop set stripchar=!teststring:~0,1! set teststring=!teststring:~1! if "!teststring!" EQU "" goto stringloop if "!stripchar!" NEQ ";" goto striploop goto stringloop ) :END endlocal
FOR %%A IN (1 2 3) DO ECHO %%A
FOR %A IN (1 2 3) DO ECHO %A
1 2 3
The following code will split a string with N number of substrings with # separated values. You can use any delimiter
@echo off if "%1" == "" goto error1 set _myvar="%1" :FORLOOP For /F "tokens=1* delims=#" %%A IN (%_myvar%) DO ( echo %%A set _myvar="%%B" if NOT "%_myvar%"=="" goto FORLOOP ) goto endofprogram :error1 echo You must provide Argument with # separated goto endofprogram :endofprogram
If someone need to split a string with any delimiter and store values in separate variables, here is the script I built,
FOR /F "tokens=1,2 delims=x" %i in ("1920x1080") do ( set w=%i set h=%j ) echo %w% echo %h%
Explanation: 'tokens' defines what elements you need to pass to the body of FOR, with token delimited by character 'x'. So after delimiting, the first and second token are passed to the body. In the body %i refers to first token and %j refers to second token. We can take %k to refer to 3rd token and so on..
Please also type HELP FOR in cmd to get a detailed explanation.