2

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.

Jimm Chen
  • 3,411
  • 3
  • 35
  • 59
  • 1
    http://stackoverflow.com/questions/7522740/counting-in-a-for-loop-using-dos-batch-script – Marc B May 28 '15 at 14:26
  • I recommend leaving behind `cmd.exe` shell scripting and use PowerShell instead. It's far superior in nearly every conceivable way. – Bill_Stewart May 28 '15 at 14:45

2 Answers2

3

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
)
Aacini
  • 65,180
  • 12
  • 72
  • 108
2

I suggest letting a tool do the enumeration for simplicity:

( for %%g in (%pattern%) do @echo %%g ) | find /n /v ""
user1016274
  • 4,071
  • 1
  • 23
  • 19