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

前端 未结 6 783
挽巷
挽巷 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 01:12

    @echo off
    setlocal EnableDelayedExpansion
    
    rem Load file lines into "line" array
    set "num=0"
    for /F "usebackq delims=" %%a in ("theFile.txt") do (
       set /A "num+=1"
       set "line[!num!]=%%a"
    )
    
    rem Select one random line
    set /A "rnd=%random% %% num + 1"
    set "IP=!line[%rnd%]!"
    
    echo %IP%
    

    For further details on array management in Batch files, see this post.

提交回复
热议问题