首页 > 解决方案 > 从批处理文件中的文件中选择随机行

问题描述

我正在尝试从一个长文本文件Character_Picker.bat中回显一个随机选择的字符串。characters.txt我不知道如何进行随机选择。

字符.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%

标签: stringbatch-filegenerator

解决方案


我想这就是你想要的。

@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。然后我们读取文件并 findstr 行号,如果该数字与随机字符串匹配,则打印该字符串。

只是为了让你了解这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=:使用:as 分隔符,我们将行号分配给%%i实际行文本,因此%%j匹配然后打印%%i%rand%%%j


推荐阅读