2016-05-19 4 views
2

多くのサブフォルダのそれぞれからN個のランダムファイルを抽出するコードがあります。感嘆符付きのファイルを除いて正常に動作します。遅延拡張を使用して、2番目のforループの感嘆符を消去します。 2番目のループで展開を無効にすると、中間結果(File1、File2、File3 ...)を取り込むために変数内の変数を使用できなくなります。助けて!遅延拡張はCatch22の状況にあります

@echo off 
chcp 1254 
REM Display N random episodes from each sub-folder in g:\itunes\podcasts 
setlocal EnableDelayedExpansion 
set /p COUNT=Select Desired Number of Random Episodes per Album: 
REM Recurse the podcast directory 
for /d %%f in (G:\itunes\Podcasts\*) do (
set "buffer=%%f" 
    set n=0 
REM http://stackoverflow.com/questions/18945521/need-to-create-a-batch-file-to-select-one-random-file-from-a-folder-and-copy-to 
    for %%g in ("!buffer!\*") do (
    set /A n+=1 
    set "file!n!=%%g" 
) 
for /l %%i in (1, 1, !COUNT!) do (
set /A "rand=(!n!*!random!)/32768+1" 
REM http://stackoverflow.com/questions/9700256/bat-file-variable-contents-as-part-of-another-variable 
for %%A in ("!rand!") do echo !file%%~A! 
) 
) 
+3

forループ内で 'call:label parameters'を使ってサブ関数を呼び出します。その後、あなたは遅延拡張を必要としません。 –

+0

@Noodlesはあなたのコメントに基づいて答えを出します。しかし、私は生の 'call:setfile'を使ってパラメータを指定しないでください。代わりに変数 'buffer' _before_' call:setfile'を設定してください。最後の 'for %% A'ループの代わりに別のサブルーチン':echofile'を呼び出すことを検討してください。 – JosefZ

+0

あるいは、遅延拡張をトグルして、必要に応じてのみ有効にし、 '%% i 'のような' for'変数を読むときに無効にするようにします。 'endlocal'の後に環境(変数)の変更がなくなったとみなす必要があります... – aschipfl

答えて

1

Windows batch file - Pick (up to) four random files in a folderが正解です。サブフォルダを許可するようにそのソリューションを修正しました。次のコードは、指定されたフォルダの各サブフォルダからN個のランダムファイルを返します。

@echo off 
REM Display N random episodes for each podcast folder (~20 min.) 
REM Solution Template found at: https://stackoverflow.com/questions/10978107 
chcp 1254 
setlocal disableDelayedExpansion 
set /p COUNT=Select Desired Number of Random Episodes per Album: 
REM This loop captures the subfolder names and sends them to loop1 
for /d %%f in (G:\itunes\Podcasts\* H:\itunes\Podcasts\*) do (
set /a ind = 0 
set buffer="%%f" 
call :loop1 %buffer% 
) 

:loop1 
    for /f "tokens=* delims=" %%g in ('dir %buffer% /a:-h-s-d /b /s') do (
    setlocal enableDelayedExpansion 
    for %%N in (!ind!) do (
    endlocal 
REM The following dynamically creates variables, WP1, WP2 ... which are later randomized 
    set "wp%%N=%%g" 
    ) 
    set /a ind += 1 
) 

setlocal enableDelayedExpansion 
for /l %%g in (1, 1, %COUNT%) do (
    set /a "num = (((!random! & 1) * 1073741824) + (!random! * 32768) + !random!) %% %ind%" 
    for %%N in (!num!) do echo !wp%%N! 
) 
関連する問題