我正在使用Windows批处理脚本。我发现了一种将变量设置为文本文件中随机行的方法。它是从第4行开始并且响应!current_proxy!
的块。从Windows批处理文本文件中获取随机行
我试图将这个块复制到批处理文件的不同部分(其周围有大的空白部分),以便在某些文件无法下载时我可以获得另一个随机行。为什么这次不工作?我是否使用错误的符号(如%
和!
)?谢谢。
@echo off
setlocal EnableDelayedExpansion
set proxies_list="proxies.txt"
:: # Count the number of lines in the text file and generate a random number.
for /f "usebackq" %%c in (`find /V /C "" ^< %proxies_list%`) do set lines=%%c
set /a random_number=%RANDOM% * lines/32768 + 1, skiplines=random_number-1
:: # Extract the line from the file.
set skip=
if %skiplines% gtr 0 set skip=skip=%skiplines%
for /f "usebackq %skip% delims=" %%c in (%proxies_list%) do set "current_proxy=%%c" & goto continue
:continue
echo/!current_proxy!
for %%a in (xml\*.xml) do (
for /l %%b in (0,1,337) do (
set /a "x=%%b%%26"
set /a "y=%%b/26"
set /a "tile_number=%%b+1"
if not exist "C:\Users\User\Desktop\panoid\tiles\%%~na\%%~na_tile!tile_number!.jpg" (
echo C:^\Users^\User^\Desktop^\panoid^\tiles^\%%~na^\%%~na_tile!tile_number!.jpg
"C:\Portable programs\wget64.exe" --read-timeout=10 --tries=3 -e use_proxy=on -e http_proxy=!current_proxy! -O "C:\Users\User\Desktop\panoid\tiles\%%~na\%%~na_tile!tile_number!.jpg" "http://updatethis.com"
FOR /F "usebackq" %%d IN ("C:\Users\User\Desktop\panoid\tiles\%%~na\%%~na_tile!tile_number!.jpg") DO set size=%%~zd
if !size! GTR 0 (
echo File not empty.
) ELSE (
echo File empty.
for /f "usebackq" %%c in (`find /V /C "" ^< %proxies_list%`) do set lines=%%c
set /a random_number=%RANDOM% * lines/32768 + 1, skiplines=random_number-1
set skip=
if %skiplines% gtr 0 set skip=skip=%skiplines%
for /f "usebackq %skip% delims=" %%c in (%proxies_list%) do set "current_proxy=%%c" & goto continue
:continue
echo/!current_proxy!
)
)
)
)
pause
每个在括号化代码块内部变化的变量都必须使用延迟扩展(例如'!skiplines!','!skip!'和'!RANDOM!')来读取。 **但是:**延迟扩展不能在'for/F'的选项字符串中使用,所以'!skip!'在那里不起作用;因此您必须将'for/F'循环移入子例程;然后你可以提供'!skip!'作为参数,并在子例程中作为'%1'访问它,该函数在'for/F'的选项字符串中运行... – aschipfl
另请参阅[this answer](http ://stackoverflow.com/a/39653402)... – aschipfl