0

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 
1
  • What have you tried, where are you stuck? Please share your coding attempts; consult this help topic: minimal reproducible example Commented Oct 5, 2018 at 11:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.