有两个文件:" list.txt"和新的" newlist.txt"。
请告诉我可以将随机行从一个文件复制到另一个文件的脚本。
要复制的行数也是随机的(在指定范围内):
set min=1
set max=100
set /a numberoflines=%random%%%(max-min+1)+min
答案 0 :(得分:-1)
虽然你没有表现出任何解决任务的努力,但我决定提供一个脚本,因为这听起来对我很有挑战性;所以这里的代码应该做你想要的:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "MIN=1" & rem // minimum number of lines to copy
set "MAX=100" & rem // maximum number of lines to copy
set "NODUPS=" & rem /* set this to non-empty value to avoid duplicates */
for /F "delims=" %%C in ('^< "list.txt" find /C /V ""') do set /A "COUNT=%%C"
if defined NODUPS (
if %COUNT% GTR %MAX% (
set /A "NUMBER=%RANDOM%%%(MAX-MIN+1)+MIN"
) else if %COUNT% GEQ %MIN% (
set /A "NUMBER=%RANDOM%%%(COUNT-MIN+1)+MIN"
) else set /A "NUMBER=COUNT"
) else (
set /A "NUMBER=%RANDOM%%%(MAX-MIN+1)+MIN"
)
call :GENRAND RND_NUM %NUMBER% %COUNT% %NODUPS%
> "lines.tmp" (
for /F "delims=" %%L in ('findstr /N /R "^" "list.txt"') do (
setlocal DisableDelayedExpansion
for /F "tokens=1 delims=:" %%N in ("%%L") do set /A "LIN_NUM=%%N"
set "LINE=%%L"
setlocal EnableDelayedExpansion
set /A "INDEX=0"
for %%I in (!RND_NUM!) do (
set /A "INDEX+=1" & set "PADDED=0000!INDEX!"
if %%I EQU !LIN_NUM! (
echo(!PADDED:~-5!:!LINE:*:=!
)
)
endlocal
endlocal
)
)
setlocal DisableDelayedExpansion
> "newlist.txt" (
for /F "delims=" %%L in ('sort "lines.tmp"') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
echo(!LINE:*:=!
endlocal
)
)
endlocal
endlocal
del /Q "lines.tmp"
exit /B
:GENRAND RND_NUM %NUMBER% %COUNT%
set "%1="
if not "%~4"=="" goto :NODUPS
for /L %%I in (1,1,%2) do (
set /A "RND_ITEM=!RANDOM!%%%3+1"
set "%1=!%1! !RND_ITEM!"
)
goto :HALT
:NODUPS
for /L %%I in (1,1,%3) do (
set /A "RND_ITEM=!RANDOM!%%%3+1"
set /A "RND[!RND_ITEM!_%%I]=%%I"
)
set /A "INDEX=0"
for /F "tokens=2 delims==" %%J in ('set RND[') do (
set /A "INDEX+=1"
set "%1=!%1! %%J"
if !INDEX! GEQ %2 goto :HALT
)
:HALT
exit /B
除非您将变量NODUPS
设置为非空值,否则随机行可能包含重复项。