0

My requirement is simple, i just want to scan all the files in the current directory for a particular string and if that string is found i just want a display saying "String is found" otherwise "String not found"

    @ECHO OFF
    for %%f in (C:\Users\aalvoor\Desktop\BatchScript\*) do (
    echo File is %%f
    find /c "defaultModel" %%f >NUL
    if %errorlevel% equ 1 (echo File is notfound) else (echo String is found)
    )

But the problem is it works when i am not putting it in a for loop but when i put it in for loop for some reason for every file i get a message String is found which is not true.

Ajesh
  • 59
  • 1
  • 1
  • 5
  • 2
    I recommend to open a [command prompt](https://www.howtogeek.com/235101/), run `if /?` and read the output help which explains already on first page the recommended syntax to evaluate the exit code of a former run command or executable. So use `if errorlevel 1` instead of `if %errorlevel% equ 1` and the code works and you have not to think about delayed expansion. See also [single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564) and chapter 4 of [this answer about dynamic variables](https://stackoverflow.com/a/65979943/3074564). – Mofi Apr 18 '21 at 09:57
  • Extremely thankful guys..if errorlevel worked...Moreover did not have to use delayedvariable expansion logic, was struggling over this over a week. Actually used the comment given by Mofo.. So how can I mark it as accepted answer? – Ajesh Apr 20 '21 at 06:26

1 Answers1

1

Use conditional operators && and ||

&& being if errorlevel equ 0

|| being if errorlevel neq 0

@echo off
for %%f in ("%userprofile%\Desktop\BatchScript\*") do (
    echo File is %%f
    find /c "defaultModel" %%f >nul 2>&1 && echo String found || echo String NOT found
)
Gerhard
  • 22,678
  • 7
  • 27
  • 43