Home > Enterprise >  Not Another Batch File Nested For Loop Question?
Not Another Batch File Nested For Loop Question?

Time:12-11

I'm trying to find a way to make nested for loops work, but this iteration is different than the most popular results (where an OP is looping through directories, or using a numerical for /l loop, etc.)

Instead, I'm trying to figure out how to make this work:

@echo Off
setlocal enabledelayedexpansion enableextensions


for /f "Tokens=1-7 Delims=_" %%P in ("Testing_This_GREAT_Thing_Of_An_IDEA") do (
  Echo %%P
  For %%a in (P Q R S T U V ) do (
    Call set "term=%%%%%%a"
    Call echo !term!
    Call set term=%%term%%
    Call Echo !term!
    Call set term=%%term%%
    Call Echo !term!
    If not "!term!"=="" Call set word.%%a=%%term%%
    Echo word.%%a = "!word.%%a!"
  )
)
pause
exit /b

Desired output of For %%a in (P Q R S T U V) loop would be to have:

word.P=Testing
word.Q=This
word.R=GREAT
word.S=Thing
word.T=Of
word.U=An
word.V=IDEA

Obviously the following would be as expected for the initial loop, but I cannot get the delayed expansion (I assume) to work as expected. . . .

%%P=Testing
%%Q=This
%%R=GREAT
%%S=Thing
%%T=Of
%%U=An
%%V=IDEA

CodePudding user response:

No, it's not possible (in a single block).

You try to dynamically access a FOR meta variable, but FOR meta variables are recognized only in the parsing phase, before the code block is executed. An inline call can't help here, because a FOR meta variable isn't detected at all in the second parsing round of a call command.

But you could use a helper function, using the fact that you can access all FOR meta variables in any FOR block, even when they are not in the same block.

@echo Off
setlocal enabledelayedexpansion enableextensions


for /f "Tokens=1-7 Delims=_" %%P in ("Testing_This_GREAT_Thing_Of_An_IDEA") do (
  Echo %%P
  For %%a in (P Q R S T U V ) do (
    Call :read_meta_var term %%a
    If not "!term!"=="" Call set word.%%a=%%term%%
    Echo word.%%a = "!word.%%a!"
  )
)
pause
exit /b

:read_meta_var
REM *** %1=Variable to store the result
REM *** %2=Character of the meta variable to read

for %%d in ("dummy") do (
  set "%1=%%%2"
)
  • Related