Batch Renamer

As promised in the Flexible Renamer article, here is my solution for renaming a series of files according to a text file. This could be useful for renaming tracks in an album from 01.mp3, 02.mp3 to 01 - Song 1.mp3 or for episodes in a TV series.

I used CMD programming which was quite a challenge (its pretty limited but most problems can be solved with a lock of hackery), but requires no additional files:

@ECHO OFF & SETLOCAL enableextensions enabledelayedexpansion
:: ---------------------------------------------------------
:: Rename.cmd by Mark Challoner
:: Renames a set of files according to a text file (one name per line)
::
:: Pattern variables:
::   $#: Line number
::   $L: Line text (after only)
::   $N: Previous name (after only)
::   $X: Previous extension (after only)
::    *: Any number of unknown characters (before only)
::    ?: One unknown character (before only)
:: ---------------------------------------------------------
:: File to get names from (no quotes)
SET file=Filenames.txt
:: Before and after filename patterns.
SET before="*.tmp"
SET after="$# - $L ($N).$X"
:: --------------------------------------------------------
:: Do not edit below this following line
SET c1=1
IF NOT EXIST "%file%" (
  ECHO %file% not found. Script will now exit.
  PAUSE
  GOTO :EOF
)
FOR /F "usebackq tokens=* delims=" %%A IN ("%file%") DO (
  IF !c1! LSS 10 (SET number=0!c1!) ELSE (SET number=!c1!)
  SET text=%%A
  SET old=%before:$#=!number!%
  SET c2=1
  FOR /F "usebackq delims=" %%B IN (`dir /b !old!`) DO (
    IF !c1! == !c2! SET old="%%B"
    SET /A c2+=1
  )
  FOR /F %%B IN (!old!) DO (
    SET old_name=%%~nB
    SET old_ext=%%~xB
    SET old_ext=!old_ext:~1!
  )
  SET new=%after:$#=!number!%
  FOR /F "delims=" %%B IN ("!text!") DO SET new=!new:$L=%%B!
  FOR /F "delims=" %%B IN ("!old_name!") DO SET new=!new:$N=%%B!
  FOR /F "delims=" %%B IN ("!old_ext!") DO SET new=!new:$X=%%B!
  IF EXIST !old! (REN !old! !new!)
  SET /A c1 += 1
)

Copy and paste into notepad, edit variables and save as Rename.cmd. Alternatively download from below. You will need a file to hold the new names (Filelist.txt here). Then doubleclick to run. Enjoy! :)

Rename.cmd

Share and Enjoy:
  • Facebook
  • Digg
  • del.icio.us
  • Sphinn
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • MySpace
  • Technorati
  • Reddit
  • TwitThis
  • RSS
  • E-mail this story to a friend!

Tags: , ,

Leave a Reply