Setup Dictionary in batch

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Sounak@9434
Posts: 100
Joined: 16 Dec 2016 22:31

Setup Dictionary in batch

#1 Post by Sounak@9434 » 08 Mar 2017 07:42

This is my third request in this week, wow.
Anyway this time I want to set a dictionary data type in batch which........is not possible by default.
So I was thinking about some workaround and thought about assigning the values as variables.
I have a sample script here that takes items from one script and sets values from the corrosponding other script.
And it is telling me each time it has a problem "!count! delims=," was unexpected at this time."
I just don't get what is wrong. Any Ideas?

Code: Select all

@echo on
setlocal enabledelayedexpansion
set font=a,b,c,d,e
set char=apple,ball,cat,dog,elephant
for /f "delims=," %%a in ("%font%") do (
   set /a count+=1
   for /f "tokens=!count! delims=," %%c in ("%char%") do (
      set "%%a=%%c"
   )
   set %%a
)
>nul timeout /nobreak /t -1

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Setup Dictionary in batch

#2 Post by Aacini » 08 Mar 2017 08:06

You can not use Delayed Expansion in the FOR /F "!options!" string.

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set font=a,b,c,d,e
set char=apple,ball,cat,dog,elephant
set charX=%char%
for %%a in (%font%) do (
   for /f "tokens=1* delims=," %%c in ("!charX!") do (
      set "dict[%%a]=%%c"
      set "charX=%%d"
   )
)
set dict[

>nul timeout /nobreak /t -1

Output:

Code: Select all

dict[a]=apple
dict[b]=ball
dict[c]=cat
dict[d]=dog
dict[e]=elephant

EDIT: Simpler?

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set char=apple,ball,cat,dog,elephant,donkey,blue,red
for %%a in (%char%) do (
   set "word=%%a"
   for %%b in ("!word:~0,1!") do set "dict[%%~b]=!dict[%%~b]! %%a"
)
set dict[

>nul timeout /nobreak /t -1

Output:

Code: Select all

dict[a]= apple
dict[b]= ball blue
dict[c]= cat
dict[d]= dog donkey
dict[e]= elephant
dict[r]= red

Antonio

Sounak@9434
Posts: 100
Joined: 16 Dec 2016 22:31

Re: Setup Dictionary in batch

#3 Post by Sounak@9434 » 08 Mar 2017 09:42

@Aacini: Thanks Aacini. Both of your script worked beautifully. :D
By The Way,
Aacini wrote:You can not use Delayed Expansion in the FOR /F "!options!" string.

I tried to avoid delayed expansion inside "options" script and still it fails.

Code: Select all

@echo on
set count=1
setlocal enabledelayedexpansion
set font=a,b,c,d,e
set char=apple,ball,cat,dog,elephant
for /f "delims=," %%a in ("%font%") do (
   set /a count+=1
   for %%b in (!count!) do for /f "tokens=%%b delims=," %%c in ("%char%") do (
      set "%%a=%%c"
   )
   set %%a
)
>nul timeout /nobreak /t -1

CMD does gets real angry to see a variable expansion inside "options". :mrgreen:

Post Reply