2016-08-16 147 views
3

我試圖做一個批處理文件,通過一個數組,包含這樣的數字循環:1 2 3 4 5. 在循環的第一個循環中,我喜歡挑選標記1和2.在第二和第三,第三和第四,等等。變量作爲令牌的for循環

我認爲我應該使用!在我用作令牌的第一個和第二個變量中。像第一個FOR/F一樣,但是當我這樣做時,我得到了:!第一!「在這裏沒有預料到

如果我使用%,它不會計數 除了變量標記之外, ?一個knowes如何任何幫助或建議大大appriciated 這是部Im struggeling有:

setlocal EnableDelayedExpansion 
set first=1 
set second=2 
set N=4 
set output="1 2 3 4 5" 
set output=%output:"=% 

for /L %%a in (1,1,%N%) do (
    if !counter! equ active (
     set /a first+=1 
     set /a second+=1 
    ) 
     FOR /F "tokens=!first!" %%a IN ("%output%") DO (
     set nr1=%%a 
     ) 
     FOR /F "tokens=%second%" %%a IN ("%output%") DO (
     set nr2=%%a 
     ) 

    echo nr1 var: !nr1! 
    echo nr2 var: !nr2! 
    echo counter f: !first! 
    echo counter s: !second! 
    set counter=active 
) 

回答

1

不能使用延遲擴展型變量在for /F選項字符串中你也不能使用其他for變量。 。但是你可以使用通常(立即)擴展的變量。例如,你也可以使用參數引用,如%1

所以一個很好的變通你的問題是將for /F循環在子程序和主程序與延遲擴展變量作爲自變量使用call,像這樣:

@echo off 
setlocal EnableDelayedExpansion 
set /A first=1 
set /A second=2 
set /A N=4 
set "output=1 2 3 4 5" 

set "counter=" 
for /L %%a in (1,1,%N%) do (
    if defined counter (
     set /A first+=1 
     set /A second+=1 
    ) 

    call :SUB !first! !second! 

    echo nr1 var: !nr1! 
    echo nr2 var: !nr2! 
    echo counter f: !first! 
    echo counter s: !second! 
    set "counter=active" 
) 
endlocal 
exit /B 

:SUB val_token1 val_token2 
for /F "tokens=%~1,%~2" %%a in ("%output%") do (
    if %~1 LSS %~2 (
     set "nr1=%%a" 
     set "nr2=%%b" 
    ) else if %~1 GTR %~2 (
     set "nr1=%%b" 
     set "nr2=%%a" 
    ) else (
     set "nr1=%%a" 
     set "nr2=%%a" 
    ) 
) 
exit /B 

由於你正在從同一個字符串中提取令牌,我將你的兩個for /F循環合併爲一個。子程序:SUB中的for /F循環中的if塊在那裏,以防萬一第二個令牌編號並不總是大於第一個。但如果能夠保證,for /F循環只需要包含set "nr1=%%a"set "nr2=%%b"