从批处理文件中的文件中随机选择一行

时间:2018-08-21 11:36:28

标签: string batch-file generator

我正在尝试制作一个Character_Picker.bat,以回显来自长文本文件characters.txt的随机选择的字符串。我不知道如何随机选择。

Characters.txt:

Disco Jockey Acid Pol
Double Agent Acid Pol
Muaythai Acid Pol
Paramedic Acid Pol
WWII Acid Pol
WWII Acid Pol
PB Quinn Chou
Secret Agent Chou
Rider Chou
General Chou
Grim Reaper Chou
Psycho Nurse Chou
Highschool Chou
Invasion Chou
Army Agent Chou
Kung Fu Chou
Rogue Agent Chou
Sweet Heart Chou
.
.
.
.333 strings more

我的批处理代码:

@echo off
color a
cd Desktop
start "characters.txt"  ==> this is the thing where I stuck
set /a string=%random% %% 334
echo %string%

2 个答案:

答案 0 :(得分:0)

我想这就是你想要的。

@echo off
set /a rand=%random% %% 334
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "d:\characters.txt"') do (
if "%%i"=="%rand%" echo %%j
)

我们设置rand并将随机数限制为334。 然后,我们读取文件并找到行号,如果该行号与随机字符串匹配,则打印该字符串。

只是为了您了解delims=:部分。 findstr /n .* "d:\characters.txt"将打印行号,然后打印冒号和实际行。像这样:

1:Disco Jockey Acid Pol
2:Double Agent Acid Pol
3:Muaythai Acid Pol
4:Paramedic Acid Pol
5:WWII Acid Pol
....

delims=:使用:作为分隔符,我们将行号分配给%%i,将实际行文本分配给%%j,因此将%%i与{{1 }},然后打印%rand%

答案 1 :(得分:0)

我首先要确定文本文件中的行数,然后确定该范围内的随机数,然后准确地提取该行,如下所示:

@echo off
for /F %%C in ('^< "characters.txt" find /C /V ""') do set "COUNT=%%C"
set /A "NUMBER=%RANDOM%%%%COUNT%"
if %NUMBER% gtr 0 (set "SKIP=skip=%NUMBER%") else (set "SKIP=")
for /F usebackq^ %SKIP:skip=skip^%^ delims^=^ eol^= %%L in ("characters.txt") do (
    echo(%%L
    goto :NEXT
)
:NEXT

如果目标行为空,则此代码将返回下一个非空行。