Simple batch script for file renaming

Ever ended up with 100 files you need to rename? Like removing  ” copy” from each filename after a batch Photoshop action? Or removing ” (small)” after resizing a big folder of images using the Image Resizer Powertoy? When you start looking online for a tool to do this most of them are commercial software, even for something so outwardly simple.

Here’s something I wrote a while ago for a colleague who runs Photoshop actions. It seemed like an easy challenge but the script actually took a while to figure out, mainly because I was determined that it should call no additional programs. I managed in the end using a couple of neat tricks: delayed variable expansion, and the little-known string replace function of the Set command. I also allowed drag & drop for the target folder containing the files you want renaming.

The script below targets .jpg files but I’ve highlighted the lines you would need to edit to change its behaviour:

::simple batch file renamer
::
::EXPLANATION - delayed variable expansion must be enabled since we want to
::expand the vars on each pass, not just once as the whole FOR loop is parsed.
::The SET command includes some simple string substitution methods (see SET /?)
::Below, I am setting newname=oldname with " (small)" substituted to ""
::The script displays what it's about to do before it does it and also supports
::dragging and dropping of the target folder.
::
@echo off
setlocal ENABLEDELAYEDEXPANSION
set folderpath=
if "%~1"=="" (
  echo No target folder was dragged ^& dropped - using local directory.
) else (
  echo Opening folder %1
  set folderpath=%1\
)
echo.
call :rename echo
echo.
echo Proceed with rename? (CTRL-C to cancel).
pause
call :rename
goto :eof

:rename
for %%i in (%folderpath%*.jpg) do (
  set oldname=%%~ni%%~xi
  ::to replace " (Small)" with ""
  set newname=!oldname: ^(Small^)=!
  %1 ren "%%~fi" "!newname!"
)
Advertisements

One thought on “Simple batch script for file renaming

  1. Pingback: Batch recursive FFmpeg transcoding script « Fixing the annoying IT stuff

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s