I've got some batch code that selects three random files from a folder (and its subfolders), but it's possible for it to end up selecting the same file more than once. I'd like it to always select unique files.
It creates a temporary text file with all the options, so I've tried to get it to remove the selected line and subtract one from the total file count each time one is selected, so that it's removed from the pool of options.
Here's the whole thing:
@echo off
setlocal
:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
set "tempFileTwo=%temp%\%~nx0_fileList2_%time::=.%.txt"
pushd %1
dir /b /s /a-d *.mov *.mp4 | findstr /n "^" >"%tempFile%"
popd
:: Count the files
for /f %%N in ('type "%tempFile%" ^| find /c /v ""') do set cnt=%%N
for /l %%N in (1 1 3) do call :openRandomFile
:: Delete the temp files
del "%tempFile%"
del "%tempFileTwo%"
exit /b
:openRandomFile
set /a "randomNum=(%random% %% cnt) + 1"
for /f "tokens=1* delims=:" %%A in (
'findstr "^%randomNum%:" "%tempFile%"'
) do (
start "" "%%B"
echo Selection: %%B
set /a cnt -= 1
findstr /l /v "%%B" "%tempFile%" > "%tempFileTwo%"
copy /y "%tempFileTwo%" "%tempFile%"
)
exit /b
The part that doesn't work is:
findstr /l /v "%%B" "%tempFile%" > "%tempFileTwo%"
copy /y "%tempFileTwo%" "%tempFile%"
I was hoping my findstr would find the selected file and remove it, and copy everything else over, but it apparently matches everything and copies a totally blank file. Not sure what I'm doing wrong.
There's a good chance that
findstr /l /v /C:"%%B" "%tempFile%" > "%tempFileTwo%"
may restore sanity.
If %%B
contains spaces, then each individual word in "%%B"
will be matched. The /c:
instructs findstr
to treat the quoted string as a string to match, not a list of substrings.
An easier way to achieve your objective would be:
In your main routine, before the pushd
:: remove variables starting $
FOR /F "delims==" %%b In ('set $ 2^>Nul') DO SET "%%b="
where $
can be any string you might desire, like #opened
. This line clears any variable that starts $
.
And in :openRandomFile
, after setting randomNum
,
if defined $%randomNum% goto openRandomFile
set $%randomNum%=Y
which establishes a flag $%randomnum%
to prevent the number from being processed more than once.
I'm sure you can work out that adjusting the tempfiles can then be removed - including the decrement of cnt
...