Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to know current loop index inside a for loop?

Tags:

batch-file

cmd

I have a .bat file like this:

@echo OFF

if "%1" == "" (
    set pattern=*
) else (
    set pattern=%1
)

for %%g in (%pattern%) do echo   %%g

Executing listfile.bat setenv*.bat, it outputs something like:

  setenv-win7x64-chk.bat
  setenv-win7x64-fre.bat
  setenv-winxp-chk.bat
  setenv-winxp-fre.bat

My question is: How can I make it output like:

[1]  setenv-win7x64-chk.bat
[2]  setenv-win7x64-fre.bat
[3]  setenv-winxp-chk.bat
[4]  setenv-winxp-fre.bat

Is there a secret variable that tells me the current loop-index? -- just like Autohotkey's A_Index variable.

like image 820
Jimm Chen Avatar asked Oct 18 '25 01:10

Jimm Chen


2 Answers

The answer is "no", but you may add a counting variable in a very simple way:

@echo OFF
setlocal EnableDelayedExpansion

if "%1" == "" (
    set pattern=*
) else (
    set pattern=%1
)

set i=0
for %%g in (%pattern%) do (
   set /A i+=1
   echo [!i!]  %%g
)
like image 193
Aacini Avatar answered Oct 20 '25 14:10

Aacini


I suggest letting a tool do the enumeration for simplicity:

( for %%g in (%pattern%) do @echo %%g ) | find /n /v ""
like image 21
user1016274 Avatar answered Oct 20 '25 14:10

user1016274