Search code examples
windowsbatch-filefor-loopfindstr

Batch Unable to echo for loop variable if findstr fails


I am trying to create a string that searches for each line in a text file and if there is a match it does nothing but if it finds a line without a match it echoes to an output text file.

@echo off
setlocal enabledelayedexpansion 
for /f "tokens=* delims= " %%a in (C:\listtocheck.txt) do (
    findstr /i %%a C:\master.txt
    if %errorlevel%==1 (echo !%%a! >> "c:\results.txt")
    )

I have no idea how I can make this work, and cant find any good working examples to reference to.

MASTER FILE
KB3216916   
KB3214051  
KB4012373


LISTTOCHECK FILE
HotFixID   
KB2849697  
KB2849696  
KB2841134  
KB2670838  

Any Help would be appreciated


Solution

  • To make your batch work you could use instead of if %errorlevel%==1:

    1. if errorlevel 1 see if /?
    2. if !errorlevel!==1 see delayed expansion

    But I suggest using conditional execution instead. Changed pathes to current directory.

    @echo off
    Type Nul > results.txt
    for /f "tokens=* delims= " %%a in (listtocheck.txt
    ) do findstr /i "^%%a" master.txt >Nul 2>&1 ||(>>"results.txt" echo %%a)
    Type results.txt
    

    Another simpler way is to use the findstr's /V + /G options which reverses the order:

    > findstr /i /V /G:Master.txt LISTTOCHECK.txt >results.txt
    

    Sample output of results.txt:

    HotFixID
    KB2849697
    KB2849696
    KB2841134
    KB2670838