Home > Software engineering >  How to copy random files from one folder to another (a batch file)
How to copy random files from one folder to another (a batch file)

Time:05-05

I am a newb in programming, I just need a simple script to select random files (15 pc.) from a folder, which contains multiple other folders too.

The code below copies the same picture each time I execute the script, so randomizer does not work. Also is there a way to exclude some special extensions from the search? Like I have 100 folders with mostly .png and .jpeg files, but also some other extension. Can it be exlcluded?

Thank you.

@echo off
setlocal EnableDelayedExpansion
cd "D:\temp\"
set n=0
for %%f in (*.*) do (
    set /A n =1
    set "file[!n!]=%%f"
)

for /L %%i in (1,1,%time:~-1%) do set "dummy=!random!"
set /A "rand=(n*%random%)/32768 1"
copy "!file[%rand%]!" "D:\temprandom\" 

CodePudding user response:

Here is an example:

@echo off
setlocal enabledelayedexpansion
pushd "D:\temp\" || goto :EOF

for /f "tokens=1,* delims=[]" %%i in ('dir /b /s /a-d ^| findstr /RV "[.]jpg [.]png" ^| find /v /n ""') do (
    set "file%%i=%%~j"
    set "cnt=%%i"
)
for /l %%c in (1,1,15) do (
        set /a rand=!random! %% !cnt!
        for %%r in (!rand!) do copy "!file%%r!" "D:\temprandom\"
)
popd

Note that the findstr /RV "[.]jpg [.]png" in both for loops are indicating the file extensions to exclude from the search.

What you need to understand is that based on the dir /s command, it can run for a long time especially if you have a lot of, so do not expect speed to be the hero of the day here.

  • Related