hackjutsu
hackjutsu

Reputation: 8922

Looping string split by spaces

I have a string "-a valueA -b valueB -c valueC", and I want to use bat to split this string by white space and parse the the value "-a" "valueA" "-b" "valueB" "-c" and "valueC" one by one.

Basically, I want to use the for loop to achieve this, however the for loop in bat seems to be far more complicated than I imagine.

I have tried the following codes but obviously it doesn't work.

set TEST_CODE="-a valueA -b valueB -c valueC"
for /f "tokens=* delims= " %%a in (%TEST_CODE%) do (
  echo %%a
)

I'm expecting the output to be

-a    
valueA    
-b   
valueB   
-c  
valueC

I refer to this link, but I'm still confused what exactly is tokens and delims here. Can some bat expert share some ideas on this?

Upvotes: 2

Views: 1416

Answers (2)

Squashman
Squashman

Reputation: 14290

Two options for you.

set TEST_CODE=-a valueA -b valueB -c valueC
for /f "tokens=1-6 delims= " %%a in ("%TEST_CODE%") do ( 
    echo %%a
    Echo %%b
    echo %%c
    Echo %%d
    Echo %%e
    Echo %%f
 )

Or

set TEST_CODE=-a valueA -b valueB -c valueC
for  %%a in (%TEST_CODE%) do echo %%a 

And one more option since the answer you picked was a CALL to a function.

call :loop -a valueA -b valueB -c valueC
pause
goto :eof

:loop
IF NOT "%1"=="" (
    echo %~1
    SHIFT
    GOTO loop
)
GOTO :EOF

Upvotes: 2

RGuggisberg
RGuggisberg

Reputation: 4750

Here's one way to do it. Calls recursive subroutine. The last line is not really needed but I put it there for safety (in case you were to comment out the 'if...goto...' line above it). By way of explanation, you call the subroutine passing the entire string. It strips off the 1st token and calls itself with the remainder of the string until the string is empty.

@echo off
call :GetToken "-a valueA -b valueB -c valueC"
pause
goto :eof

:GetToken
for /f "tokens=1*" %%a in ("%~1") do (
  echo(%%a
  if "%%b"=="" goto :eof
  call :GetToken "%%b"
)
goto :eof

Upvotes: 3

Related Questions