2017-05-03 27 views
1

我有一些代碼的麻煩中,我真的不知道該怎麼形容它 但我可以解釋一下什麼行不通麻煩與使用變量循環批處理

FOR /D /r "%cd%\files\" %%G in ("*") DO (
    echo In folder: %%~nxG 
    set /a count=1 
    echo %%~fG 

    For /R "%%~fG" %%B in ("*.mp3") do (
     call :subroutine "%%~nB" 
) & echo. >>%archive%.txt 

) 

剛如果你想知道子程序做什麼:

:subroutine 
echo %count%:%1>>%archive%.txt 
echo %count%: %1 
set /a count+=1 
GOTO :eof 

我想通了,它不讀取第二個for循環裏面的%%~fG。 有人可以幫助我嗎。

我使用SETLOCAL EnableDelayedExpansion

預先感謝您。

回答

1

不幸的是你將需要另一個子程序,因爲在外部標記之前解析選項。檢查下面的例子:

@echo off 

echo :::ATTEMPT 1::: 
for %%a in (z) do (
    rem the expected delimiter is z and result should be ++::%%a 
    for /f "delims=%%a tokens=1,2" %%A in ("++z%%%%az--") do echo %%A::%%B 
) 


echo :::ATTEMPT 2::: 
for %%a in (z) do (
    call :subr "%%~a" 
) 

exit /b 

:subr 
rem the expected delimiter is z and result should be ++::%%a 
for /f "delims=%~1 tokens=1,2" %%A in ("++z%%%%az--") do echo %%A::%%B 

輸出爲:

::: ATTEMPT 1 :::

++Ž:: zz--

::: ATTEMPT 2 :::

++ :: %%一個

正如您在第一次嘗試中看到%%a符號被視爲分隔符。但子例程參數會立即被解析,因此可以使用它們。 要使您的代碼正常工作,您可以嘗試:

FOR /D /r "%cd%\files\" %%G in ("*") DO (
    echo In folder: %%~nxG 
    set /a count=1 
    echo %%~fG 

call ::innerFor "%%~fG" 

) 
... 
exit /b %errorlevel% 
:innerFor 
    For /R "%~1" %%B in ("*.mp3") do (
     call :subroutine "%%~nB" 
) & echo. >>%archive%.txt 
1
For /R "%%~fG" %%B in ("*.mp3") do (

不幸的是,for/r不能使用變量作爲dirname運行。

我建議

call :anothersubroutine "%%~fG" 

和 :anothersubroutine 對於( 「* .MP3」)做(

  • 但I」/R 「%〜1」 %%乙也許你需要將set %%〜fG變成一個變量,並使用%var%(沒有試過,要麼......)