using batch, i want to be able to separate a variable into two or three parts, when there is a symbol dividing them. for example if i have the string which looks like this: var1;var2;
how can i get var1 to become variable and var2 to become a different one.
Thanks in Advance
Tokens=1,2
does create the two for loop variables%%i
and%%j
& splitsstring
in two parts, separated by the delimiter;
:For a more "dynamic" method use this:
The best way to split a variable into an array (or as close to an array as Windows batch can imitate) is to put the variable's value into a format that can be understood by a
for
loop.for
without any switches will split a line word-by-word, splitting at csv-type delimiters (comma, space, tab or semicolon).This is more appropriate than
for /f
, which loops line-by-line rather than word-by-word, and it allows splitting a string of an unknown number of elements.Here's basically how splitting with a
for
loop works.The important part is the substitution of
;
into","
in%var%
, and enclosing the whole thing in quotation marks. Indeed, this is the most graceful method of splitting the%PATH%
environment variable for example.Here's a more complete demonstration, calling a subroutine to split a variable.
Here's the output of the above script:
Just for fun, try un-commenting the
set string=%PATH%
line and let the good times roll.If you got only "one" appears, change the line
by