Search code examples
batch-filerandomcopylines

Batch script to copy random lines from one text file to another


There are two files: "list.txt" and new "newlist.txt".

Please tell me the script that can copy random lines from one file to another.

The number of lines to copy is also random (in the specified range):

set min=1
set max=100
set /a numberoflines=%random%%%(max-min+1)+min

Solution

  • This should work:

    @echo off
    setlocal EnableDelayedExpansion
    type nul >newlist.txt
    set min=1
    set max=100
    set /a numberoflines=%random%%%(max-min+1)+min
    set /a cnt=0
    for /f %%a in ('type "list.txt"^|find "" /v /c') do set /a cnt=%%a
    FOR /L %%G IN (1,1,%numberoflines%) DO (
      set /a "linenumber=!random!%%%cnt%"
      set "read=1"
      set "line=-1"
      for /F "usebackq delims=" %%i in ("list.txt") do (
        set /a "line=!line!+1
        if !line! equ !linenumber! echo %%i >>newlist.txt
      )
    )
    

    Note that I put a type nul >newlist.txt at the start to clear newlist.txt before copying. If you only want to add the lines to the file, you should remove it.