0

Having such simple batch script

@echo off
for /F "tokens=*" %%f in (toFind.txt) do (

    find /c "%%f" 1.txt
    
    if errorlevel 0 (
        echo %%f "--->" found 
    )   else (
        echo %%f "--->" not found!
    )
)

it ALWAYS returns ... found even if the string (from a toFind.txt file) IS'T exist in the 1.txt file...

1
  • 2
    Could you clear up your last sentence?
    – harrymc
    Jan 27, 2021 at 17:40

2 Answers 2

1

You are using the old IF ERRORLEVEL syntax from MS-DOS.

IF ERRORLEVEL N do_something means "If errorlevel is greater than or equal to N do_something"

Since ERRORLEVEL will always be greater than or equal to 0, you will always get the "found" message even when FIND returns a nonzero error.

What you want is the Windows NT modern version where errorlevel is a proper variable.

IF %errorlevel% equ 0 do_something

However you are in a loop so you need delayed expansion and you use ! instead of % around errorlevel

IF !errorlevel! equ 0 do_something

so try this

@echo off
setlocal enabledelayedexpansion
for /F "tokens=*" %%f in (toFind.txt) do (

    find /c "%%f" 1.txt
    
    if !errorlevel! equ 0 (
        echo %%f "--->" found 
    )   else (
        echo %%f "--->" not found!
    )
)
1

1. You can use operators (&& == return 0 and || == return non 0) instead errolevel

2. Use/add Usebackq in your For /F loop, this will output the lines one by one as if in double quotes, avoiding possible failures where the lines contain &, (, ), |, &, <, >, etc.

3. By using setlocal EnableDelayedExpansion, the "!" will not be treated as a character, failing to compare lines where it contains in both files.

@echo off 

for /f usebackq^tokens^=* %%f in (toFind.txt
    ) do find/c "%%~f" <1.txt >nul && (
         echo\%%~f ---^> found!
    ) || echo\%%~f ---^> not found!

Additional resources:

1
  • The Additional Resources section was very useful. Much appreciated!
    – Keve
    May 6, 2023 at 11:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .