Search code examples
batch-filebatch-rename

Edit names of image database with batch files


I have a folder with 460 images with 23 per person in the format: image_0001.jpg to image_0460.jpg. What is the batch command to rename them in the form 01-01.jpg to 01-23.jpg for a person and thus the entire database upto 20-23.jpg? [EDIT] I came across:

@echo off & setlocal EnableDelayedExpansion 

set a=1
for /f "delims=" %%i in ('dir /b *') do (
  if not "%%~nxi"=="%~nx0" (
    ren "%%i" "!a!" 
    set /a a+=1
 ) 
) 

I could not find a way to use loop variables to do the same. Is there a way to use loop variables or is there another way?


Solution

  • @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET "sourcedir=U:\sourcedir"
    SET /a filenum=10000
    FOR /L %%a IN (1,1,20) DO (
     FOR /L %%b IN (1,1,23) DO (
      SET /a filenum+=1
      SET /a newnum=10000+%%b+(%%a*100^)
      ECHO(REN "%sourcedir%\image_!filenum:~-4!.jpg" "!newnum:~1,2!-!newnum:~-2!".jpg
     )
    )
    GOTO :EOF
    

    You would need to change the setting of sourcedir to suit your circumstances.

    The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

    The issue is one of leading zeroes, hence invoke delayedexpansion and calculate using 10000+a significant number, then substring.

    The rest is simply a matter of mathematics.