Batch files for Adding random numbers (3 digits) i

2019-09-15 19:43发布

问题:

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.

回答1:

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...



回答2:

  • To get a random number with 3 places you can do a modulus division by 1000
  • to get leading zeroes for numbers below 100 you can add 1000 and only use the last 3 places of the number.
  • to ease the splitting of the number I'd use a delimiter like _

 @Echo off & Setlocal EnableDelayedExpansion
 Set "Delims=_"
 for %%i in (*.mp3) do (
     Set /A RndNum=1000+!Random! %% 1000
     Echo Ren "%%i" "!RndNum:~-3!%Delims%%%i" 
 )
 Pause

For testing purposes the ren command is prepended with an echo, remove it when the output is OK.

@Echo off
Set "Delims=_"
For /F "tokens=1,* Delims=%Delims%" %%A in (
    'Dir /B "???%Delims%*.mp3" '
) do Echo ren "%%A%Delims%%%B" "%%B"
Pause