Search code examples
windowsbatch-filerandomcommand-linebatch-rename

Batch files for Adding random numbers (3 digits) in front of files and for removing the numbers


I'm interested in 2 batch files: one that generates random numbers (3 digits) and puts them in front of every MP3 file in a folder, and the other batch for removing these random numbers.

My attempt at the first batch:

@echo off
setlocal EnableDelayedExpansion 
for %%i in (*.mp3) do ( ren "%%i" "!RANDOM!%%i" ) 
endlocal

The problem: the numbers are up to 5 digits.

My attempt at the second batch:

@echo off
setlocal enableextensions enabledelayedexpansion 
for %%i in (*.mp3) do (set name=%%i && ren "!name!" "!name:~3!") 
endlocal

The problem: it removes 6 characters from the first file.


Solution

  • Perhaps you could be interested in these two Batch files that I wrote some time ago:

    Scramble songs.bat:

    @echo off
    setlocal EnableDelayedExpansion
    
    rem Scramble *.mp3 files inserting a random number in their names
    rem Antonio Perez Ayala
    
    rem Create a list of numbers in natural order for all files
    rem with four digits each and a separation space
    cd "%~DP0\My Music in 4GB"
    set i=10000
    set "list="
    for %%a in (*.mp3) do (
       set /A i+=1
       set "list=!list!!i:~-4! "
    )
    set /A i-=10000
    
    rem Extract random elements from the list of numbers
    rem and use they in the new name of the files
    for /F "delims=" %%a in ('dir /B *.mp3') do (
       echo !i!-  "%%a"
       set /A "randElem=!random! %% i * 5, i-=1"
       for %%r in (!randElem!) do for /F %%s in ("!list:~%%r,4!") do (
          setlocal DisableDelayedExpansion
          ren "%%a" "%%s- %%a"
          endlocal
          set "list=!list:%%s =!"
       )
    )
    
    pause
    

    Unscramble songs.bat:

    @echo off
    setlocal DisableDelayedExpansion
    
    rem Unscramble the *.mp3 files removing the random number from their names
    rem Antonio Perez Ayala
    
    cd "%~DP0\My Music in 4GB"
    for /F "tokens=1*" %%a in ('dir /B *.mp3') do (
       echo %%a  "%%b"
       ren "%%a %%b" "%%b"
    )
    
    pause
    

    The first Batch file insert a four-digits number before each song because my 4GB card can accept more than 1000 songs, but I am pretty sure you may modify this code in order to reduce the number to 3 digits...