Search code examples
batch-filetailfindstr

Batch file to output last line of findstr


I am trying to find a list of machines in files in folders, and print out the last line of the output only.

@echo off
for /f %%a in (computers.txt) do findstr /xs "%%a" unhealthy.txt
pause

The computers.txt file has a list of 300 machines.

I want that to output only the last line of each instance it finds.

Right now the command displays and outputs all instances of the computer name, not just the tail end. I've tried to use "tail for Windows" but am getting errors as well.

Current output:

2013\10-Oct\28\unhealthy.txt:WIN57505
2013\10-Oct\29\unhealthy.txt:WIN57505
2013\10-Oct\30\unhealthy.txt:WIN57505
2013\10-Oct\31\unhealthy.txt:WIN57505
2013\11-Nov\1\unhealthy.txt:WIN57505
2013\11-Nov\4\unhealthy.txt:WIN57505
2013\11-Nov\5\unhealthy.txt:WIN57505
2013\11-Nov\6\unhealthy.txt:WIN57505

I only want:

2013\11-Nov\6\unhealthy.txt:WIN57505


Solution

  • @echo off
    setlocal enableextensions disabledelayedexpansion
    for /f %%a in (computers.txt) do (
        set "line="
        for /f "tokens=*" %%b in ('findstr /xs "%%a" *') do set "line=%%b"
        setlocal enabledelayedexpansion
        echo(!line!
        endlocal
    )
    pause
    endlocal