Nick Sinas
Nick Sinas

Reputation: 2634

batch file to return next to last line of text file

I have a file that contains the output of a file compare thats written to a text file:
Comparing files C:\LOGS\old.txt and C:\LOGS\NEW.TXT
***** C:\LOGS\old.txt
***** C:\LOGS\NEW.TXT
folder_thats_different
*****

I need to pull out the next to last line "folder_thats_different" and put in a new string:
folder contains a file that is different: folder_thats_different

Yes, I know I can use another language, but I'm stuck with batch files for now.

Upvotes: 4

Views: 10446

Answers (3)

Patrick Gilliland
Patrick Gilliland

Reputation: 1

The first answer works for me. I also added 2 lines after the end to allow it to repeat so I could watch an active log file without having to close and reopen it. I do a lot of debugging for the mods that are used in the game Space Engineers. My version looks like this:

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%x in (SpaceEngineers.log) do (
    set "previous=!last!"
    set "last=%%x"
)
echo !previous!
timeout 15 /nobreak
se_log

The line below stops the batch file from looping too fast and stop the key bypass. To change the amount of time in seconds just change the number "15" to anything you want. To stop the batch file just press ctrl+c.

timeout 15 /nobreak

The line below is the name of the batch file I made so it will tell CMD to run this again.

se_log

Upvotes: 0

Michael Burr
Michael Burr

Reputation: 340188

Here's an example you can use as a starting point. Just change the filename in the set command= line to the appropriate name (or replace the command with whatever will gerneate the log listing).

@echo off
@setlocal

(set command=type test.txt)

for /f "usebackq tokens=*" %%i in (`%command%`) do call :process_line %%i
echo next to last line: %old_line%
goto :eof

:process_line
(set old_line=%new_line%)
(set new_line=%*)
goto :eof

Of course, you'll probably want to do something other than simply echoing the found line.

Upvotes: 0

jeb
jeb

Reputation: 82247

You can try to read it with a for-loop and take the current line, and always save the previous line

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%x in (myFile.txt) do (
    set "previous=!last!"
    set "last=%%x"
)
echo !previous!

Upvotes: 3

Related Questions