Home > other >  Renaming files sequentially with 4 digits - .bat
Renaming files sequentially with 4 digits - .bat

Time:09-17

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
)

CodePudding user response:

Working solution below, thanks to aschipfl who did show me the way and Stephan

@echo off

setlocal enableextensions enabledelayedexpansion

set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%i in (`powershell %psCommand%`) do set "folder=%%i"

cd %folder%

set path=%folder:~1%
    for %%i in ("%path%") do (
        set "parent=%%~ni"
    )

set /a count=10000
    for /F "eol=| delims=" %%f in ('dir /B /A:-D-H-S /O:N "*.tif"') do (
        set /a count =1
        set fileName=!parent!_!count:~-4!%%~xf
        rename "%%f" "!fileName!"
)

exit /b

CodePudding user response:

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)

  • Related