Script to extract the last word in the last line of a text file

2

I am trying to extract the last word of a findstr results query

The command I run

findstr /i %1 x:\itlogs\who_when.txt | findstr /i %2

the results I get

12/02/2018 10:17:58     SmithS         Steve Smith                     B0K9VY1
13/02/2018 09:29:13     SmithS         Steve Smith                     B0K9VY1

What I need from the results is that last word B0K9VY1 so i can run SCCM RemoteControl $computername

(it will always be the last word on the last line of the results from my findstr query)

Chris Page

Posted 2018-02-13T22:23:06.843

Reputation: 23

Answers

1

What I need from the results is that last word B0K9VY1

Try the following batch file and tweak to taste:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=6" %%i in ('findstr /i %1 x:\itlogs\who_when.txt ^| findstr /i %2') do (
  set last_word=%%i
  SCCM RemoteControl !last_word!
  )
endlocal

But I only want the last word of the last line, not every line!

Move echo !last_word! outside of the for loop as follows:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=6" %%i in ('findstr /i %1 x:\itlogs\who_when.txt ^| findstr /i %2') do (
  set last_word=%%i
  )
SCCM RemoteControl !last_word!
endlocal

Further Reading

DavidPostill

Posted 2018-02-13T22:23:06.843

Reputation: 118 938

Worked well thanks. How do i filter it to only the very last entry? Currently it is listing every line (but only the machine name now which is great) – Chris Page – 2018-02-13T23:17:10.457

@ChrisPage So you only want the last word on the last line? Move echo !last_word! outside of the for loop. And replace the echo with SCCM RemoteControl – DavidPostill – 2018-02-13T23:25:29.370