2

On Windows Command Line I would like to loop over a list the following way:

list = 1,2,4,8,4,1,5

for /f %x in list do (echo %x)

But the above does not work, so how one loop over a list with the Windows Command line?

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
george
  • 151
  • 1
  • 3
  • 7

3 Answers3

3

Save this as a batch file and run it from Command Prompt.

@echo off

set mylist=does,this,work

for %%i in (%mylist%) do (
  echo %%i
)
DanielG
  • 1,669
  • 1
  • 12
  • 26
  • thanks but is it possible without making a batch file ? – george Sep 26 '16 at 15:13
  • @george Just do `for %x in (%list%) do echo %x`. Use a single `%` for the loop variable outside of a batch file. – Ross Ridge Sep 26 '16 at 16:12
  • Using the loop variable is quite hard in `()` if you want to do anything fancy. [Here](https://stackoverflow.com/questions/13805187/how-to-set-a-variable-inside-a-loop-for-f) it tells how to actually make use of the value: Use `call :WhatToDo %%i`. – Quirin F. Schroll Jul 21 '23 at 10:35
0

The FOR command is mostly used to process files, but you can also process a text string:

FOR %X IN ("1" "2" "3") DO Echo %X
P.Bra
  • 264
  • 1
  • 12
0

PowerShell:

1,2,4,8,4,1,5 | ForEach-Object { $_ }

PowerShell has built-in support for lists and has a far more consistent syntax than cmd.exe. I would recommend giving it a try.

Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62