Batch file to delete half the lines of a text file at random?

前端 未结 6 380
囚心锁ツ
囚心锁ツ 2021-01-29 11:27

I need a way to use batch to look at every line of a text file, and delete half of the lines in that text file, choosing which lines to delete at random.

This is to simu

6条回答
  •  失恋的感觉
    2021-01-29 12:08

    This method preserve the order of original lines.

    @echo off
    setlocal EnableDelayedExpansion
    
    rem Generate an array of line numbers with all file lines
    for /F "delims=:" %%a in ('findstr /N "^" input.txt') do (
       set "n[%%a]=%%a"
       set "lines=%%a"
    )
    
    rem Delete half the numbers in the array in random order
    set /A halfLines=lines/2
    for /L %%n in (%lines%,-1,%halfLines%) do (
       set /A rnd=!random!*%%n/32768+1
       set /A n[!rnd!]=n[%%n]
       set "n[%%n]="
    )
    
    rem Reorder the resulting elements
    for /F "tokens=2,3 delims=[]=" %%i in ('set n[') do (
       set "l[%%j]=1"
       set "n[%%i]="
    )
    
    rem Copy such lines
    (for /F "tokens=1* delims=:" %%a in ('findstr /N "^" input.txt') do (
       if defined l[%%a] (
          echo(%%b
          set "l[%%a]="
       )
    )) > output.txt
    

提交回复
热议问题