Randomly select a line out of a text file and set that line as a variable

前端 未结 6 781
挽巷
挽巷 2021-01-22 00:29

How to randomly select a line/ip out of a text file, and set it as a variable.

I mean something like:

set IP=TheLine/IPFromOfTheFile
6条回答
  •  遥遥无期
    2021-01-22 00:53

    Firstly you need to know the number of lines present in the text file textfile.txt:

    for /F %%N in ('type "textfile.txt" ^| find /C /V ""') do set NUM=%%N
    

    Then calculate the random number in the range from 0 to NUM-1:

    set /A RND=%RANDOM%%%NUM
    

    Finally pick the line from the text file and store it in LINE. RND holds the number of lines to skip by the for /F loop:

    if %RND% EQU 0 (set "SKIP=") else (set "SKIP=skip=%RND% ")
    for /F "usebackq %SKIP%delims=" %%L in ("textfile.txt") do (
        set "LINE=%%L"
        goto :NEXT
    )
    :NEXT
    

    This relies on the fact that the text file does not contain any empty lines.

提交回复
热议问题