I have a mp3 player that has a poorly designed hard coded random generator for shuffling songs. Every time I turn it on, it plays the same sequence (5-22-3-150-75-86... etc) In order to hear a larger variety I want to be able to periodically randomize the file names on the usb stick and alter the files position in the directory listing.

I am trying to rename all file names in a sub-directory to a random number. This is what I have been trying but it does not work. For some reason %num% is blank in the new file name.

1|    for %%A in (*.mp3) DO (
2|    set /A num=%RANDOM%*100/32768+1
3|    ren "%%A" %num%.mp3
4|    )
5|    pause

(Line numbers added for clarity during this discussion)

The output for each file is shown below.

D:\music_playlists\pop-mix [25gb]>(
set /A num=13621*100/32768+1
ren "Country-132.mp3" .mp3
A duplicate file name exists, or the file
cannot be found.

As you can see the %NUM% is not being expanded to a file name on line #3...

What do I need to do?

update - not sure exactly what was going on but this seems to work even though the echo shows a blank field

SETLOCAL EnableDelayedExpansion

FOR %%A IN (*.mp3) DO (
echo !NUM!
REN "%%A" !NUM!.mp3


2 Answers 2


Try enabling delayed expansion and changing the % signs used with RANDOM and NUM to ! points:

SETLOCAL EnableDelayedExpansion

FOR %%A IN (*.mp3) DO (
SET /A NUM=!RANDOM!*100/32768+1
REN "%%A" !NUM!.mp3


If the random number has already been chosen, does any file have the same name? Thus, will fail

In general, yes, so in these situations, you will need to get another random number to rename the file with a unique name/number.

May I suggest taking the range of two decimal places further, evasively decreasing the likelihood of repetition when renaming files?

@Echo Off & SetLocaL EnableDelayedExpansion

For /F Tokens^=* %%A In ('DIR /ON/B *.Mp3')Do Call :^) "%%~DPA" "%%~NXA"
Endlocal && goto :EOF

For /F %%F In ('Set /A _Num^=!Random!*1000/32768+1')do Set "_Num=100%%F"
If Not Exist "%~1!_Num:~-4!.MP3" Ren "%~1%~2" "!_Num:~-4!.MP3" & Exit /B
Goto :^)
  • Why do you use the :^) characters for the routine label? Sep 4, 2019 at 4:30
  • @PimpJuiceIT so, for short and nice options...
    – Io-oI
    Sep 4, 2019 at 4:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.