Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get each item of a comma separated string assigned to an environment variable processed within a loop?

The FOR loop only outputs the first item of the list and I'm trying to go over the whole list.

@ECHO OFF
set list=this,is,a,list
FOR /f "tokens=1* delims=," %%a IN ("%list%") DO echo %%a
pause
like image 463
RedBelly Avatar asked Jun 04 '16 14:06

RedBelly


People also ask

How do you extract comma Separated Values in Python?

Python String split() Method Python split() method splits the string into a comma separated list. It separates string based on the separator delimiter. This method takes two parameters and both are optional. It is described below.

What is %% f in batch script?

To avoid confusion with the batch parameters, %0 through %9 , you can use any character for variable except the numerals 0 through 9. For simple batch files, a single character such as %%f will work. You can use multiple values for variable in complex batch files to distinguish different replaceable variables.


2 Answers

The FOR /F command split a line in several tokens, that must be referenced individually via separate letters:

@ECHO OFF
set list=this,is,a,list
FOR /f "tokens=1-4 delims=," %%a IN ("%list%") DO (
   echo %%a
   echo %%b
   echo %%c
   echo %%d
)
pause

The plain FOR command process a series of elements separated by space, or by the standard Batch file delimiters: comma, semicolon or equal-sign:

@ECHO OFF
set list=this,is,a,list
FOR %%a IN (%list%) DO echo %%a
pause
like image 191
Aacini Avatar answered Nov 09 '22 07:11

Aacini


Open a command prompt window, run for /? and read the output help.

With tokens=1* the first string delimited by 1 or more commas (,,, is like 1 comma!) is assigned to loop variable a which is here the word this. And the rest of the string being is,a,list is assigned to loop variable b (next after a in ASCII table) which is not referenced at all in provided code snippet.

Here is a batch code demonstrating how to process each substring of a comma separated string:

@echo off
set "List=this,is,a,list"
set ItemCount=0

:NextItem
if "%List%" == "" pause & goto :EOF

set /A ItemCount+=1
for /F "tokens=1* delims=," %%a in ("%List%") do (
    echo Item %ItemCount% is: %%a
    set "List=%%b"
)
goto NextItem

The output is:

Item 1 is: this
Item 2 is: is
Item 3 is: a
Item 4 is: list

There are of course also other solutions possible. This is just an example.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • set /?
like image 41
Mofi Avatar answered Nov 09 '22 07:11

Mofi