Search code examples
windowsbatch-filecmd

Renaming files sequentially with 4 digits - .bat


I'm looking for a solution to my problem, below the script I'm using, I found it here, changed it, it was working the way I wanted to for what I was doing but now I want to do that and I'm struggling with the answer.

Example:

<br>Open_university_MS221_0001.tif</br>
<br>Open_university_MS221_0001-2.tif</br>
<br>Open_university_MS221_0002.tif</br>
<br>Open_university_MS221_0002-2.tif</br>
<br>etc.</br>
<br>Open_university_MS221_0001.tif</br>
<br>Open_university_MS221_0002.tif</br>
<br>Open_university_MS221_0003.tif</br>
<br>Open_university_MS221_0004.tif</br>
<br>etc.</br>
@echo off
setlocal enableextensions enabledelayedexpansion
set /a count=1
for %%f in (*.tif) do (
    set FileName=%%~nf
    set FileName=000!count!
    set FileName=!FileName:~-4!
    for /F "tokens=1-3 delims=_+" %%g in ('dir /b /od *.tif') do ( 
        set prefix=%%g_%%h_%%i
    )
    set FileName=!prefix!_!Filename!%%~xf
    rename "%%f" "!FileName!"
    set /a count+=1
)

Solution

  • You can get rid of a lot of code within the loop, when you initialize the counter to 10000 before entering the loop. Then within the loop, you just use !count:~-4!

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set /a count=10000
    for %%f in (*.tif) do (
        for /F "tokens=1-3 delims=_+" %%g in ('dir /b /od *.tif') do ( 
            set prefix=%%g_%%h_%%i
        )
        set /a count+=1
        set FileName=!prefix!_!count:~-4!%%~xf
        rename "%%f" "!FileName!"
    )
    

    The code could be shortened even more but at the cost of readability.

    Oh - and I moved set /a count+=1 up to avoid starting with 0000 (your example shows, you don't want that)