Friday, August 10, 2012

Tokenize a string in batch

Earlier today I needed to pass a string to a function, and then split it into multiple tokens.
In my case I was looping through a large set of data in the function, and I wanted to compare it with multiple strings I was searching for.

Here's how I did it, with comments to explain =)
@echo off

call :TEST "String 1;String 2;String 3"
goto :EOF

set str=%1                         REM Set the variable 'str' to the argument passed.
set str=%str:;=";"%                REM This is where the magic happens. Replaces all ';' characters in the string with '";"'
                                   REM This makes turns "String 1;String 2" into "String 1";"String 2"
for %%A in (%str%) do echo %%~A    REM And then we can loop through them and print them out one at a time.
goto :EOF

No comments:

Post a Comment