Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through comma separated string in batch?

Tags:

batch-file

Windows

Based on the post (dos batch iterate through a delimited string), I wrote a script below but not working as expected.

Goal: Given string "Sun,Granite,Twilight", I want to get each theme value in loop so that I can do some processing with the value.

Current output is not corrct:

list = "Sun,Granite,Twilight" file name is "Sun Granite Twilight" 

For the first iteration it should be:

list = "Sun,Granite,Twilight" file name is "Sun" 

Then second iteration should be "file name is "Granite" and so on. What am I doing wrong?

Code:

set themes=Sun,Granite,Twilight  call :parse "%themes%" goto :end  :parse setlocal set list=%1 echo list = %list% for /F "delims=," %%f in ("%list%") do (     rem if the item exist     if not "%%f" == "" call :getLineNumber %%f     rem if next item exist     if not "%%g" == "" call :parse "%%g" ) endlocal  :getLineNumber setlocal echo file name is %1 set filename=%1 endlocal  :end 
like image 425
Meow Avatar asked Jun 18 '13 00:06

Meow


2 Answers

This is the way I would do that:

@echo off set themes=Sun,Granite,Twilight echo list = "%themes%" for %%a in ("%themes:,=" "%") do (    echo file name is %%a ) 

That is, change Sun,Granite,Twilight by "Sun" "Granite" "Twilight" and then process each part enclosed in quotes in a regular (NO /F option) for command. This method is much simpler than an iterative for /F loop based on "delims=,".

like image 197
Aacini Avatar answered Sep 25 '22 21:09

Aacini


I took Aacini's answer and only slightly modified it to remove the quotes, so that the quotes can be added or removed as it would be in the desired command.

@echo off set themes=Hot Sun,Hard Granite,Shimmering Bright Twilight for %%a in ("%themes:,=" "%") do (     echo %%~a ) 
like image 33
Brent Avatar answered Sep 23 '22 21:09

Brent