延迟扩张让我陷入了Catch22的境地

时间:2016-05-19 04:13:50

标签: batch-file

我有从许多子文件夹中提取N个随机文件的代码。除了带有感叹号的文件外,它工作正常。我使用延迟扩展,它会消除第二个for循环中的感叹号。如果我在第二个循环禁用了扩展,那么我将无法使用变量中的变量来捕获中间结果(File1,File2,File3 ......)。救命啊!

@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!
)
)

1 个答案:

答案 0 :(得分: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!
 )