Skip to content

Instantly share code, notes, and snippets.

@iforwms
Last active January 29, 2016 15:03
Show Gist options
  • Save iforwms/b27d39a6358823da92e5 to your computer and use it in GitHub Desktop.
Save iforwms/b27d39a6358823da92e5 to your computer and use it in GitHub Desktop.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
echo.
echo ============================================================
echo.
echo RANDOM FILE RENAMER
echo.
echo by Ifor Waldo Williams ^<ifor@designedbywaldo.com^>
echo.
echo.
echo Assign or prefix a random number to all files in the
echo current directory (file extensions will be preserved).
echo.
echo ============================================================
echo.
echo Please make your selection
echo.
echo.
echo p - PREFIX each file with a random number
echo.
echo r - RENAME each file to a random number
echo.
echo q - QUIT
echo.
echo.
:makeSelection
set /P selection="Type selection and press enter: "
rem User chose to quit, so go to end of file.
if %selection%==q (
goto :eof
)
rem Set prefix variable to true and process the files.
if %selection%==p (
echo.
echo Prefixing files...
set prefix=1
goto :processFiles
)
rem Set prefix variable to false and process the files.
if %selection%==r (
echo.
echo Renaming files...
set prefix=0
goto :processFiles
)
rem If no valid choice was made, go back to the selection menu.
echo.
echo Invalid selection, please try again.
echo.
echo.
goto makeSelection
:processFiles
rem Loop through all files in current folder and rename or prefix
rem filenames with random number.
rem Double percentage signs are required when used within a batch file.
for /f "tokens=*" %%a in ('dir /b *.*') do (
rem Ignore the script file itself
if not %%a==%~nx0 (
rem Set default suffix to current file extension, e.g. ".mp3".
set suffix=%%~xa
if %prefix%==1 (
rem Set suffix to current filename with underscore,
rem e.g. _song-2.mp3.
set suffix=_%%a
)
rem Create the new filename.
set newFilename=!random!-!random!-!random!!suffix!
rem !random! is a built-in function that generates a random
rem number between 0 and 32767.
rem Rename the file.
rename "%%a" "!newFilename!"
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment