0

To convert string of words into an array in batch script, I wrote a small script

setlocal enableextensions enabledelayedexpansion
echo run

set sentence=a~b~c

set /a i=0

for /f "tokens=1,2,3 delims=~" %%a in ("%sentence%") do (
   set /a i+=1
   set array[!i!]=%%a
)

echo %array[1]%
echo %array[2]%

But there is some problem with this logic as only first element gets assigned. How can i correct this.

Rog Matthews
  • 3,147
  • 16
  • 37
  • 56

2 Answers2

3

the FOR command parses the contents of your variable into consecutive variable %a %b %c...

read HELP FOR and try, in your case,

for /f "tokens=1,2,3 delims=~" %%a in ("%sentence%") do (
   set array[1]=%%a
   set array[2]=%%b
   set array[3]=%%c
)
echo %array[1]%
echo %array[2]%

for a more generic parser loop, you will need a very tricky technique of changing your delimiters into line separators. See this SO answer https://stackoverflow.com/a/12630844/30447 for a comprehensive explanation.

Community
  • 1
  • 1
PA.
  • 28,486
  • 9
  • 71
  • 95
2

If you can space-delimit the string instead, this should work for you.

@echo off
setlocal ENABLEDELAYEDEXPANSION
REM String, with words separated by spaces
set sentence=x y z

set index=0
for %%A in (%sentence%) do (
    set Array[!index!] = %%A
    set /a index += 1
)

echo.There are %index% words
set Array

Output:

F:\scripting\stackoverflow>s2a2.cmd
There are 3 words
Array[0] = x
Array[1] = y
Array[2] = z
M Jeremy Carter
  • 433
  • 4
  • 9
  • 1
    This will print correct output on console. If i want to have three variables say var1, var2, var3 or array[1],array[2] and array[3] and i want to assign values x, y and z to them for further use, what is the correct way. – Rog Matthews Sep 12 '13 at 16:13
  • This solution does that for you. The 'set Array' command displays all variables that start with the word "Array". Variable %ARRAY[0]% is equal to "x", %ARRAY[1]% is equal to "y", and %ARRAY[2]% is equal to "z". You can use those throughout the rest of your script or at the command line. If you want to do something with all of the variables, do something like: for /f "tokens=2,* delims==[]" %%A in ('set Array') do echo.Array variable %%A is equal to %%B Let me know if I didn't understand your question. – M Jeremy Carter Sep 20 '13 at 17:58
  • @MJeremyCarter trying to print echo %Array[1]% results in ECHO is off. message – Ghos3t Mar 27 '18 at 10:38