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

前端 未结 6 898
挽巷
挽巷 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:11

    If I had gotten to this question earlier, I might've written Aacini's answer pretty much identically. He gets a +1 from me.

    Anyway, how about something different for a little variety? Here's a batch one-liner that invokes a PowerShell helper.

    for /f "delims=" %%I in ('powershell "get-random (gc \"%file%\")"') do set "IP=%%I"
    

    It's slower than Aacini's solution, but it does have the advantage of simplicity. *shrug* If your IPs file includes any empty lines, you can add a selector to include only lines whose truthiness doesn't evaluate to false / empty.

    for /f "delims=" %%I in ('powershell "gc \"%file%\" | ?{$_} | get-random"') do set "IP=%%I"
    

    I'd also thought about getting a count of the lines in the text file using find /c /v "" txtfile then using for /f "skip=%randomLineNumber%" (like aschipfl's answer), but that'd be less efficient than the other answers already offered.

提交回复
热议问题