Search code examples
batch-filetext-files

Batch file to Copy the last n lines of a text file into a new text file


is there a way using a batch file to copy the last n lines of a log file into a new text file.

Log file:

line 1
line 2
line 3
line 4
line 5

n = 2

Newfile:

line 4
line 5

Solution

  • You could try the following code:

    @echo off
    set /A "_LAST=2" & rem // (define the number of last lines to keep)
    for /F %%C in ('^< "test.log" find /C /V ""') do set "COUNT=%%C"
    set /A "LINES=COUNT-_LAST"
    if %LINES% gtr 0 (set "SKIP=+%LINES%") else (set "SKIP=")
    > "test.log.new" more %SKIP% "test.log"
    

    This script can handle log files containing empty lines and such with a length of up to 65534 characters. However, the output file must not contain more than 65535 lines. Note, that TABs become expanded to SPACEs.


    Or try this:

    @echo off
    set /A "_LAST=2" & rem // (define the number of last lines to keep)
    for /F %%C in ('^< "test.log" find /C /V ""') do set "COUNT=%%C"
    set /A "LINES=COUNT-_LAST"
    if %LINES% gtr 0 (set "SKIP=skip^=%LINES%") else (set "SKIP=")
    > "test.log.new" (
        for /F usebackq^ %SKIP%^ delims^=^ eol^= %%L in ("test.log") do (
            echo(%%L
        )
    )
    

    This one has not got a limitation for the number of lines, though the file size must be less than 2 GiB. However, it cannot handle files containing empty lines (as they get lost) and such with a length of more than 8190 characters.