從清單中隨機替換文件(批次檔)

從清單中隨機替換文件(批次檔)

我需要幫助創建批次文件。問題的關鍵是我需要隨機選擇一個檔案(從N個檔案的數量中)並將其移動到另一個目錄(替換舊檔案)

我嘗試在這裡使用這段程式碼:

for /f "usebackq delims=" %%i in ("example.txt") do (
 call set $%%random%%=%%i
 )
for /f "delims==" %%i in ('set $') do (
 replace D:\test\Z\TEST /R
 exit /b
 )

答案1

@echo off

setlocal & set "_dir=%Temp%\Test\Target\."

for /f %%f in ('type example.txt^|find/v /c ""')do set /a "_max=%%~f-1"
set /a "_line=%random% * (-%_max% - %_max% + 1) / 32768 + %_max%"

if %_line% neq 0 set "_skip=skip^=%_line:-=%"

for /f %_skip%^usebackq^ ^tokens^=*^ ^delims^= %%i in (
    "example.txt")do move/y "%%~i" "%_dir%" & endlocal & exit /b

在這種情況下,使用範圍 1 中的隨機繪製和文字檔案中的總行數來取得要複製的檔案的路徑。

1.使用範圍 -/+總行數 -1:100 lines == range [-100-1] - [+100-1]

2.將此值用於skip=?前面的行,設置,並在循環skip= resulting number中使用它。For /f

3.如果0是已排序的,則變數 toskip沒有設置,不會幹擾,使得取得第一項,不會跳過任何行。

4.無論這些行是否(0或最多 a maximumof 的其他值-1),使用該行/文件%%~i都會立即退出循環。


刪除隨機獲得的行 a 的選項...

@echo off

setlocal & set "_dir=%Temp%\Test\Target\."
for /f %%f in ('type ".\example.txt" ^| find/v /c ""
')do if %%~f geq 1 (set /a "_max=%%~f-1")else goto :eof

set /a "_line=%random% * (-%_max% - %_max% + 1) / 32768 + %_max%"
 
if %_line% neq 0 set "_skip=skip^=%_line:-=%"
for /f %_skip%^usebackq^ ^tokens^=*^ ^delims^= %%i in (
     "example.txt")do set "_file=%%~i" && goto %:^)
    
%:^)
findstr /v /c:"%_file%" <".\example.txt" >"%temp%\example.txt"
move /y "%_file%" "%_dir%" && move/y "%temp%\example.txt" ".\example.txt"
endlocal & goto :eof

相關內容