The recent batch processing command, accidentally found that there are still random numbers, before this, is not dare to think about.
When it comes to random numbers, different software has the function of random function, the use method is similar, but there is a difference.
This article gives you an introduction to the usage and example of the batch command random in MS-DOS.
Value range of random
To use random, you must use it as a variable to get the value.
Open the MS-DOS window and enter the following code to get the value.
Copy Code code as follows:
%random% can produce random numbers between 0 and 65535.
second, by obtaining a certain range of random numbers
By one, we know that%random% can produce random numbers between 0 and 32767, but how do we get a certain range of random numbers?
The general algorithm formula is as follows:
The general formula%random%%% (max-min+1) +min to generate the random number in the [Min,max] interval, note: The modulus in the batch process is two percent%.
For example, we want to get a random number between 4 and 12, so we can use the code as follows:
Copy Code code as follows:
@REM produces 10 random numbers between [4,12]
@echo off
REM enable deferred environment variable extension
Setlocal enabledelayedexpansion
REM sets the minimum and maximum values of random numbers and the variables used for modulus
Set min=4
Set max=12
set/a Mod=!max!-! min!+1
FOR/L%%i in (1,1,10) do (
REM produces a random number between [Min,max]
set/a r=!random!%%!mod!+!min!
Echo.
echo Random number%%i:!r!
)
Iii. Other examples
Instance ①: Common functions
Generate a random number from 1 to 100
Copy Code code as follows:
set/a randomnumber=%random%%%100+1
:: 100 is the range number, 1 is the base is the number of the start. (used in Bat), there will be an error in CMD.
:: Take a random two-digit number
set/a d=%random:~0,2%
Echo%d%
:: Avoid 00
set/a e=1%random:~0,2%-100
Echo%e% @echo off
: Loop
set/a randomnumber=1%random:~-1%%random:~-1%-99
:: Maximum Value 100
If%randomnumber% LSS Goto loop
:: Less than 35 return
If%randomnumber% GTR-Goto loop
:: Greater than 75 return
Echo%randomnumber%
If "%randomnumber%" = = "Pause"
Goto Loop
Instance ②: Random get filename
Copy Code code as follows:
@echo off
If "%1" NEQ "$" (
for/f "tokens=1,2 delims=:"%%a in ('%~0 ' $^|sort ') do @echo%%b
else for/f "delims="%%i in (' dir/b/a-d *.mp3 ') do @call: Sub%%i
Goto:EOF:sub
Echo%random%:%*
Goto:eof
Instance ③: Randomly fetching a row of data in one text
Copy Code code as follows:
@ECHO%dbg% off
SETLOCAL enabledelayedexpansion
for/f "tokens=*"%%i in (TEST. TXT) do (set/a h+=1 & SET r!h!=%%i)
set/a s=%random%%%%h%+1
ECHO!r%s%!