Skip to content

Instantly share code, notes, and snippets.

@Costava
Last active November 8, 2015 17:34
Show Gist options
  • Save Costava/e0b73aa5830d1f7d65ea to your computer and use it in GitHub Desktop.
Save Costava/e0b73aa5830d1f7d65ea to your computer and use it in GitHub Desktop.
Iterate over files with batch. Do work on every tenth PNG image, like deleting every tenth frame of a video if you have all of the frames as images.
:: Iterate over all .png images in current directory
:: and do work on every 10th image.
:: Assumes files are named [anything][x].png
:: where x starts at 1 (doesn't matter whether 001, 01, 1) and increments by 1.
:: Every 10th image has [x] that ends in 0.
:: The easiest way to run this script is to put it in the same directory
:: as all your images, then change to that directory in the command prompt
:: and enter the name of the file to execute it, e.g. myscript.bat
:: Makes only output display on screen
:: More info on echo: http://ss64.com/nt/echo.html
@echo off
:: "The @ symbol tells the command processor to be less verbose;
:: to only show the output of the command without showing it being
:: executed or any prompts associated with the execution."
:: - Stack Overflow user Sunny at
:: http://stackoverflow.com/questions/21074863/what-is-the-at-sign-in-a-batch-file-and-what-does-it-do
:: Necessary for variables to be updated in `for` loop
:: "Delayed Expansion will cause variables to be
:: expanded at execution time rather than at parse time"
:: Via http://ss64.com/nt/delayedexpansion.html
setLocal enableDelayedExpansion
:: Inside `for` loop, get value of a variable by putting name inside !'s
:: e.g. !myvar!
:: Inside code blocks (like a `for` loop), comments begin with rem as in "remark"
:: Using double colon (::) will result in an error.
:: More info on comments: http://www.robvanderwoude.com/comments.php
:: %%i will be "image1.png" or "image37.png" for example
for %%i in (*.png) do (
rem Make a working copy of %%i called "str"
set str=%%i
rem Remove first 5 characters,
rem assuming filenames are prefixed with "image" (5 characters)
rem Also remove last 4 characters (".png")
set str=!str:~5,-4!
rem Remove rem on next line if you want to verify
rem that image number is correctly found
rem and that every .png is checked.
rem You will also notice the order that files are checked.
rem echo Image number: !str!
rem Remove all but last character (One's digit)
set str=!str:~-1!
rem Remove rem on next line if you want
rem to verify that one's digit is correctly found
rem echo One's digit: !str!
if "!str!"=="0" (
echo Match found. Filename: %%i
rem Use whatever condition for your use case.
rem Run the script with echo to make sure that
rem the right files are selected,
rem then add your real command
rem e.g. del %%i
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment