Delayed expansion in loop body is using /f option

Asked

Viewed 124 times

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 that I need is.

When using the delayed Expansion I get the error "tokens=! n_tokens! was unexpected", I wonder what is the problem that happens and some solution too.

1 answer

2


I searched Stackoverflow in English and found a post saying that it is simply not accepted delayed Expansion in the body of the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.