2017-02-08 68 views
1

我正在使用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 
+0

每个在括号化代码块内部变化的变量都必须使用延迟扩展(例如'!skiplines!','!skip!'和'!RANDOM!')来读取。 **但是:**延迟扩展不能在'for/F'的选项字符串中使用,所以'!skip!'在那里不起作用;因此您必须将'for/F'循环移入子例程;然后你可以提供'!skip!'作为参数,并在子例程中作为'%1'访问它,该函数在'for/F'的选项字符串中运行... – aschipfl

+0

另请参阅[this answer](http ://stackoverflow.com/a/39653402)... – aschipfl

回答

0

下面是一个示例,告诉您Call :label可以提供帮助。

它使用一个稍微不同的方法,它设置在一开始就在%proxlist%每行一个变量,如果该列表是不是很大这是特别有利的。

@Echo Off 

Set "proxlist=proxies.txt" 

For /F "Tokens=1* Delims=:" %%a In ('FindStr/N "^" "%proxlist%"') Do (
    Set "line[%%a]=%%b" 
    Set "total=%%a" 
) 

Call :SetRand 
Echo=%randline% 

Call :SetRand 
Echo=%randline% 

Call :SetRand 
Echo=%randline% 

Timeout -1 
Exit/B 

:SetRand 
Set/A "rand=(%RANDOM%%%total)+1" 
Call Set "randline=%%line[%rand%]%%" 

每当你需要另一个随机行只要调用脚本的该做的部分,只是在Call命令后返回点。

+0

为什么在每个回声后暂停(“按任意键继续...”)? – grgoelyk

+0

它不会,它会在输出三条随机线后使用'timeout'暂停一次。 – Compo

+0

哦,那是因为我把“暂停”作为最后一行。这现在起作用。我删除了“Timeout -1”和“Exit/B”代码。我还必须将最后三行移到整个批处理脚本的底部,否则它将无法工作。谢谢。 – grgoelyk

相关问题