虽然我同意其他人的观点,您应该自己尝试,但这是一个相对简单的脚本,应该作为学习的一个很好的工作示例:
@ECHO OFF
SETLOCAL EnableDelayedExpansion EnableExtensions
REM Source file.
REM The first line on this file should be blank as it will never be selected.
REM Additionally, this file should have no empty lines on the end.
SET TextFile=text.txt
REM Determine the number of lines.
SET NumLines=0
FOR /F "usebackq tokens=* delims=" %%A IN (`TYPE %TextFile%`) DO SET /A NumLines=!NumLines!+1
REM Pick a random line.
SET /A RandomLine=(%RANDOM% %% %NumLines) + 1
REM Prevent skipping all the lines.
IF "%RandomLine%"=="%NumLines%" SET RandomLine=1
REM Print the random line.
FOR /F "usebackq tokens=* skip=%RandomLine% delims=" %%A IN (`TYPE %TextFile%`) DO (
ECHO %%A
REM We are done. Stop the script.
GOTO Finish
)
:Finish
ENDLOCAL
如此接近 - 但不完全。 SKIP 将始终至少为 1(因为 SKIP=0 无效)因此永远无法选择文件中的第一行。
这是我从上面得到的一个文件,有一些痒痒的。由于我的工作方式,我还更改了文件名。我正在使用包含发布的行的q27829742.txt。
@ECHO OFF
SETLOCAL
SETLOCAL EnableDelayedExpansion EnableExtensions
REM Source file.
REM The first line on this file should be blank as it will never be selected.
REM Additionally, this file should have no empty lines on the end.
SET "TextFile=q27829742.txt"
REM Determine the number of lines.
FOR /f %%a IN ('type "%textfile%"^|find /c /v ""') DO SET /a numlines=%%a
REM Pick a random line.
SET /A RandomLine=(%RANDOM% %% %NumLines%)
REM Prevent skipping all the lines.
IF "%RandomLine%"=="0" (SET "RandomLine=") ELSE (SET "RandomLine=skip=%randomline%")
REM Print the random line.
FOR /F "usebackq tokens=* %RandomLine% delims=" %%A IN (`TYPE %TextFile%`) DO (
ECHO %%A
REM We are done. Stop the script.
GOTO Finish
)
:Finish
ENDLOCAL
find /v /c 方法对文件中的行进行计数(查找不匹配的文件行 (/v) ""(这意味着所有行)并计算它们 (/c) - 更有效。
Pick-random-number :删除+ 1 会产生0..(numlines-1) 的结果,这是skip 的实际行数。
问题在于skip=0 无效,因此请构造一个其他空(对于0)或“skip=...”(否则)的字符串-一切准备就绪包含在for /f 命令选项中。
语法SET "var=value"(其中值可能为空)用于确保行尾的任何杂散空格不包含在分配的值中。 set /a 可以安全地“无引号”使用。