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.

2
  • 2
    I recommend to open a command prompt, 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 and chapter 4 of this answer about dynamic variables. Commented Apr 18, 2021 at 9: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? Commented Apr 20, 2021 at 6:26

1 Answer 1

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
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.