【问题标题】:Random file selection "validation" in Batch批量随机文件选择“验证”
【发布时间】:2017-03-13 16:45:30
【问题描述】:

美好的一天!因此,由于严格的系统限制,我必须批量完成这项任务。

它的原理是“随机”从一个文件夹中选择文件,并将它们复制到另一个文件夹中。 问题是,有时“随机性”会选择同一个文件,因此在需要的 10 个文件中,我最终得到 8-9 个。 我试图建立一个“验证”系统,但我似乎无法让它循环工作,所以它只做一次,而且它仍然有机会选择同一个文件。

对不起,如果代码是一个完整的意大利面条,我不是程序员

我有一种感觉,解决方案非常简单,我只是没有看到它 非常感谢任何形式的帮助或建议 提前谢谢你

“验证”在“sub3”中

@echo off & setlocal enableextensions disabledelayedexpansion
set "workDir=C:\Generator\Tickets"
FOR /L %%n in (1,1,10) DO call :main %%n
goto :sub3

:main
@set /a "rdm=%random%"
set /a "rdm=%random%"
pushd "%workDir%"
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do call :sub1
set /a "rdNum=(%rdm%*%counter%/32767)+1"
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do set "fileName=%%i" &call :sub2
popd "%workDir%"
goto :eof
:sub1
set /a "counter+=1"
goto :eof
:sub2
set /a "counter+=1"
if %counter%==%rdNum% (
xcopy /y "C:\Generator\Tickets\"%fileName%"" "C:\Generator\temp"
)
goto :eof

:sub3
pushd "C:\Generator\temp" && (
        for /f "tokens=1,*" %%j in ('
            robocopy . . /l /nocopy /is /e /nfl /njh /njs
       ') do ( if %%j neq 10 goto main) 
        popd
    )
goto :eof

【问题讨论】:

标签: windows loops batch-file cmd


【解决方案1】:

使用不同的逻辑:

@echo off
set "source=C:\Generator\Tickets"
set "dest=C:\Generator\temp"
REM make sure, destination is empty:
del /q "%dest%\*"
REM get number of files in source:
for /f %%a in ('dir /b /a-d "%source%\" ^|find /c /v ""') do set count=%%a
REM do ten times:
for /l %%a in (1,1,10) do call :sub
goto :eof

:sub
  REM get file index to copy [see 'set /?` for Modulo-operator]:
  set /a x=%random% %% %count% +1
  REM get filename of index:
  for /f "tokens=* skip=%x%" %%a in ('echo x^&dir /b /a-d') do set "file=%%a" & goto :cont
  :cont
  REM if file already exists in destination, try again:
  REM ATTENTION: this is an endless loop, if there are not enough files in source...
  if exist "%dest%\%file%" goto :sub
  REM else copy the file:
  copy "%source%\%file%" "%dest%\"
goto :eof

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2011-02-20
    相关资源
    最近更新 更多