1

I extracted the last line of a text file using the following command:

for /f "tokens=*" %%m in (message_log.txt) do (
   Set lastline=%%m
)

My goal is if the variable %lastline%=="☺§☻PDF file has been aborted. then to display one output and if not exit. But I think the first three characters are messing it up. I am trying this:

for /F "tokens=1-5 delims= " %%a in (%lastline%) do (
    if %%e==aborted. (
        echo pdf not filed
    )
Pause

but the file just exits, with no pause and no output.

I can get this to work if instead of using %lastline% I refer to a file as I did in the first for loop, however I cannot get it to work with a variable.

What is the correct syntax to use a FOR loop to search inside a predefined variable?

If it is simpler my ultimate goal is to echo an error message if the last line in my text file contains the string "abort". Is there a better way to do this?

1
  • 5
    You're missing a ). Open the command prompt and run the script from there instead of double-clicking it to see if there are any errors. Commented Jun 17, 2017 at 1:16

1 Answer 1

1

Your first approach is OK, just missing the check.

for /f "delims=" %%m in (message_log.txt) do Set lastline=%%m

If "%lastline%" neq "%lastline:abort=%" ^
  Echo error message the last line in message_log.txt contains the string "abort"

With findstr

for /f "delims=" %%m in (message_log.txt) do Set lastline=%%m

Echo %lastline%|Findstr /i "abort" 2>&1 >Nul && ^
  Echo error message the last line in message_log.txt contains the string "abort"

With Gnuwin32 tools installed

tail -n 1 message_log.txt|grep "abort" >NUL && ^
  Echo error message the last line in message_log.txt contains the string "abort"
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the solutions! I used the first one and it worked fantastic! I did have to get rid of the hat ^ though. I am not sure why it was there but it wouldn't recognize the next line of code if it was present.
The caret ^ as the last char is the line continuation char to split long lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.