alokin123
alokin123

Reputation: 35

Windows - read last line of text file, find word/phrase perform action

I am trying to do the following:

I have a file of which i am trying to read and if a certain phrase is found in the very last line, i want to perform an action.

This is the last few lines of the the text file

A PC is either going to have the above in the log file repeated over and over or it will not have anything close.

I essentially want to read the very last line and see if it finds "Failed to get registration state" and if it does run a script.

Here is what i have so far but i think i am nowhere near what i should be doing. Any help would be greatly appreciated as i am not very good at scripting. I was basically trying to count the number of lines and store it in a variable:

@echo off
for /f %%i in ('find /v /c "" ^< C:\Client.log') do set /a lines=%%i
set /a startLine=%lines%
for /f "tokens=*" %%a in ('findstr /i "Failed to get registration state. Error" more /e +%startLine% C:\Client.log') do echo %%a

Upvotes: 0

Views: 5598

Answers (2)

Magoo
Magoo

Reputation: 79983

@echo off
for /f "tokens=*" %%a in (C:\Client.log) do set "line=%%a"
echo "%line%"|findstr /i /c:"Failed to get registration state. Error" >nul
if errorlevel 1 (
 echo not found
) else (
 echo found
)

line will be set to the contents of each line in turn. When the for loop ends, it will contain the contents of the last line. Then test for the string, but since it contains spaces, you need /c: otherwise it would find any of the words in the quoted-string.

[edit : added @echo off line and inserted quotes around %line% in piped-echo.]

Since your target line appears to include redirectors, the quotes are required.

I conclude from your comments that your last line may be

<![LOG[RegTask: Failed to get registration state. Error: 0x8009000b]LOG]!>

Regrettably, you haven't posted examples, not have you edited your question to add-in your code so the precise layout of the code you are using (which is critical) remains a mystery.

Upvotes: 1

Aacini
Aacini

Reputation: 67216

@echo off
setlocal

rem Get the number of last line
for /f %%i in ('find /v /c "" ^< C:\Client.log') do set "lastLine=%%i"

rem Get the number of last line where target string was found
for /f "delims=[]" %%a in ('find /N /i "Failed to get registration state. Error" C:\Client.log') do set "lastFound=%%a"

if "%lastFound%" equ "%lastLine%" echo Run the script

Upvotes: 0

Related Questions