Thursday, 17 May 2018

Batch file rename with random alphanumeric

The following simple script will rename all .jpg files in the current folder to random 8 character alphanumeric names, preserving the .jpg extension. Note that it is possible for the random name generator to produce a name that already exists, so the script loops until it successfully generates a unique name.
@echo off
setlocal disableDelayedExpansion
set "chars=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for /f "eol=: delims=" %%F in ('dir /b /a-d *.jpg') do call :renameFile "%%F"
exit /b

:renameFile
setlocal enableDelayedExpansion
:retry
set "name="
for /l %%N in (1 1 8) do (
  set /a I=!random!%%36
  for %%I in (!I!) do set "name=!name!!chars:~%%I,1!"
)
echo if exist !name!.jpg goto :retry
endlocal & ren %1 %name%.jpg
A bit more code yields a versatile utility that allows you to specify the source path and file mask, and also provides the option to process sub-directories as well. The utility always preserves the extension of each file. Be careful with this utility!
renameFilesRandom.bat
:: renameFilesRandom.bat  [filter]  [/s]
@echo off
setlocal disableDelayedExpansion

:: Parse and validate arguments
set "option="
set "filter="
if "%~3" neq "" (
  >&2 echo ERROR: Too many arguments
  exit /b 1
)
if /i "%~1" equ "/S" (set "option=/S") else if "%~1" neq "" set "filter=%~1"
if /i "%~2" equ "/S" (set "option=/S") else if "%~2" neq "" (
  if defined filter (
    >&2 echo ERROR: Only one filter allowed
    exit /b 1
  ) else set "filter=%~2"
)
if "%filter:~0,1%" equ "/" (
  >&2 echo ERROR: Invalid option %filter%
  exit /b 1
)
if not defined filter set "filter=*"

:: Convert a directory filter into a file filter with wildcards
if exist "%filter%\" set "filter=%filter%\*"

:: Determine source if /S option not specified
set "src="
if not defined option for /f "eol=: delims=" %%F in ("%filter%") do set "src=%%~dpF"

:: Rename the specified files
set "chars=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for /f "eol=: delims=" %%F in ('dir /a-d /b %option% "%filter%"') do call :renameFile "%%F"
exit /b

:renameFile
setlocal
if not defined src set "src=%~dp1"
set "old=%~nx1"
set "ext=%~x1"
setlocal enableDelayedExpansion
:retry
set "name="
for /l %%N in (1 1 8) do (
  set /a I=!random!%%36
  for %%I in (!I!) do set "name=!name!!chars:~%%I,1!"
)
if exist "!src!!name!!ext!" goto :retry
ren "!src!!old!" "!name!!ext!"
Below are some sample usages.
Rename all files in the current directory:
renameFilesRandom
Rename all .jpg files in the current directory:
renameFilesRandom *.jpg
Rename all .jpg files in the c:\test folder, and all its sub-folders (recursive):
renameFilesRandom c:\test\*.jpg /s

No comments:

Post a Comment

Note: only a member of this blog may post a comment.