Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file for copying every nth file from folder1 to folder2?

I am trying to copy every 30th file from one folder to another and automate the process for other folders. I have already tried the batch script in this thread: windows batch file script to copy every tenth file from a folder to another folder and just get "The syntax in that command is incorrect" when I run the file (and yes, I've tried both versions).

My folders do have spaces in the names (not my choice and cannot be changed). The files are named image00000X.jpg and yes, there are over 100k of them (which is why I really want the script to work).

Ideally, I'd like a way to set the script up so that I could just change the input and output paths and not have to move the script between the different folders when running it but I'll settle for whatever I can get at this point because I have tried just about everything else (including robocopy, Xcopy, five Powershell scripts, and a few BASH scripts).

Thanks!

like image 605
GK Masterson Avatar asked Aug 31 '25 16:08

GK Masterson


1 Answers

Here is a simple batch file:

:: copyNth.bat  interval  sourcePath  destinationPath
@echo off
setlocal
set /a n=0
for %%F in ("%~f2.\*") do 2>nul set /a "1/(n=(n+1)%%%1)" || copy "%%F" %3

sampleUsage:

copyNth 30 "c:\someSourcePath" "d:\someDestinationPath"

The "%~f2. is syntax that allows you to safely append a file (or file mask) to any provided path.

The trick to getting every Nth value is to let SET /A intentionally raise a division by 0 error. I redirect the error message to nul and conditionally copy the file only when there was an error.

like image 90
dbenham Avatar answered Sep 02 '25 06:09

dbenham