Windows – How to Batch Rename Files by Moving Character to the End

batch-renamecmd.exerenamewindows

Having previously used batch files to rename files with success, I thought this would be possible, but I just cannot get it to work for this case.

I have the following files which I'd like to rename so that they are ordered correctly:

  • IMG_9963 – no change
  • IMG_E9963 should be renamed to IMG_9963E

So basically, if there is an E, it needs to be moved from where it is to the end of the file name. The rest of the file name should be unchanged.

There may be thousands of files to run through.

To complicate things, the filenames may already have been prefixed so the E may not always be the same place. The E will always be before the numbers though & will always be an E. So examples could be:

WorkIMG_9963
WorkIMG_E9963
AIMG_9963
AIMG_E9963

I've tried lots of different approaches, but coding is not my strength. I've only previously pre-fixed filenames etc. This is the kind of thing I was trying:

setlocal enabledelayedexpansion
for %%j in (*) do (
set old_filename=%%j
set "new_filenameA=!old_filename:E=!"
set "new_filenameB=!new_filenameA!E"
ren "!old_filename!" "!new_filenameB!"
) 

How can I automate this type of renaming task?

Best Answer

Well I'm adding this as answer since the topic got reopened now:

@echo off

setLocal EnableDelayedExpansion

if exist "%~1" (if not exist "%~1\" exit) else (exit)
pushd "%~1"
for /f "delims=" %%a in ('dir /b "%~1"') do (
                                             set Name=%%~na
                                             set Name=!Name:E=!
                                             set "NewName=!Name!E%%~xa"
                                             if not "%%~na"=="!Name!" ren "%%a" "!NewName!"
                                            )
popd
Related Question