Delayed expansion in the body of the loop is by using the / f option

2

I reduced the code to be brief:

@echo off

setlocal EnableDelayedExpansion

set /a n_tokens=2

for /f "tokens=!n_tokens! delims=\" %%s in ("Program\Executable") do (
    echo %%s
) 

pause > nul

I know that in this context it would not be necessary to use exclamations (!!) to expand the variable, but in the context I need it.

When using delayed expansion I get the error "tokens =! n_tokens! was unexpected", I would like to know what the problem is and some solution too.

    
asked by anonymous 30.08.2017 / 02:08

1 answer

2

I searched StackOverFlow in English and found a post saying simply do not accept delayed expansion in the body of for, so I decided to use the suggestion given by the user in one of the answers:

@echo off

setlocal EnableDelayedExpansion

set /a n_tokens=1

:: Este é um exemplo resumido do que eu tentava
for /f "tokens=* delims=\" %%s in ("Prog\Exe") do (
    set /a n_tokens=2

    for /f "tokens=!n_tokens! delims=\" %%s in ("Prog\Exe") do (
        REM erro !n_tokens! foi inesperado
    )
)

:: Solução que encontrei
for /f "tokens=* delims=\" %%s in ("Prog\Exe") do (
    set /a n_tokens=2

    call :Func
    REM Continuar o código...
)
goto end


:Func
:: Essa função é chamada após a atualização da variável n_tokens

for /f "tokens=%n_tokens% delims=\" %%s in ("Prog\Exe") do (
    echo %%s
    REM imprime corretamente "Exe" (segundo token de "Prog\Exe")
)

goto :eof

:end
pause > nul
    
31.08.2017 / 17:51