Windows – Rename files sequentially from input using batch file

batch filebatch-renamewindows

The company I work for processes bills, and I regularly have to check these bills for accuracy by comparing what was entered into the database vs. the actual bill image. Any time I find an error in processing, I must delete the bill from the database and send the image to a processor to re-enter the bill correctly. However, our system frequently encounters a glitch where if I try to upload the bill to the server that gets it to the processor, it says that a duplicate file exists. To bypass this issue I have to manually rename each image with a new name (we use rolls of control numbers to name our images).

I'd like to automate this process so that I can rename these files quickly in sequential order. I would like my batch file to have an input so that I can enter in the starting control number and it will rename each file in the directory in sequential order, starting with the control number I enter +1 to each additional file in the directory, for example it would go like this:

Batch file asks me starting control #. I enter in 6654821.

  • bill3210851.pdf renamed to 6654821
  • imagebill654.pdf renamed to 6654822
  • random_name.pdf renamed to 6654823
  • billerror.pdf renamed to 6654824
  • sendtomanual.pdf renamed to 6654825

The original name of the file is not at all relevant, they don't need to remain in any specific order as long as they are renamed sequentially.

So far what I have is this:

@echo OFF
title Batch Rename
color 5f

echo Hello! I'm the batch pdf renamer. Please enter the starting control number:
set /p start=

ren %userprofile%\desktop\needrenamed\*.pdf "%p%.pdf"

pause

Obviously this doesn't address renaming the files sequentially. I'm kind of stuck here.

Best Answer

This has been tested in Windows 7 Professional. No error checking of any kind is performed. It renames the files in the current directory, so the script should be somewhere on your path.

@echo off
set /p start=Please enter the starting control number: 

setlocal enableDelayedExpansion

for /r %%g in (*.pdf) do (call :RenameIt %%g)
goto :eof
goto :exit

:RenameIt
echo Renaming "%~nx1" to !start!%~x1
ren "%~nx1" !start!%~x1
set /a start+=1
goto :eof

:exit
exit /b

Hope that helps!

Related Question