g.t.w.d
g.t.w.d

Reputation: 621

Command Line Check if a string variable contains specific text

I'm looping through a list of directory names, and I'm trying to find out if a directory has certain text.

This is my cmd line code:

FOR %%a in (%%c) do (
   echo.%%a|findstr /C:"Plugin" >nul 2>&1
     if not errorlevel 1 (
       echo Found
    ) else (
      echo Not found.
    )
   )

It actually appears to work, but then after it finishes, it exits with Code 1. I have output window build set to diagnostic, but I don't see any explanation of the error. Looking for a bit of guidance or maybe a better way to do what is essentially %%a.Contains("Plugin").

Upvotes: 0

Views: 2668

Answers (1)

MC ND
MC ND

Reputation: 70943

Your loop keeps iterating after the folder has been found and that means the findstr executed for the last file failed the test and set the errorlevel to 1.

But this code can also fail if no file is present, as the do clause will not be executed so the findstr will not set the errorlevel.

If the for structure is needed (not sure, missing code)

for %%c in ..... do (
    FOR %%a in (%%c) do (
       echo.%%a|findstr /C:"Plugin" >nul 2>&1
       if not errorlevel 1 (
            echo Found
            exit /b 0
       )
    )
)
echo Not found
exit /b 1

or, you can try with

( >nul 2>&1 dir /s *plugin* ) && echo found || echo not found 

that will use the dir command to check for a matching file (and set the error level if not present) and use the conditional operators to show the text

Upvotes: 1

Related Questions