18

I am trying to create a batch (.bat) file for windows XP to do the following:

If (file.txt contains the string 'searchString') then (ECHO found it!) 
ELSE(ECHO not found)

So far, I have found a way to search for strings inside a file using the FIND command which returns the line in the file where it finds the string, but am unable to do a conditional check on it.

For example, this doesn't work.

IF FIND "searchString" file.txt ECHO found it!

Nor does this:

IF FIND "searchString" file.txt=='' ECHO not found

Any Ideas on how this can be done?

Ross Ridge
  • 37,034
  • 7
  • 72
  • 110
Jai
  • 3,491
  • 3
  • 22
  • 31

2 Answers2

17

From other post:

    find /c "string" file >NUL
    if %errorlevel% equ 1 goto notfound
        echo found
    goto done
    :notfound
        echo notfound
    goto done
    :done

Use the /i switch when you want case insensitive checking:

    find /i /c "string" file >NUL

Or something like: if not found write to file.

    find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )

Or something like: if found write to file.

    find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )

Or something like:

    find /c "%%P" file.txt  && ( echo found ) || ( echo not found )
Mike Q
  • 5,800
  • 4
  • 48
  • 56
  • 1
    Consider adding /i switch in order to get case-insensitive comparison. Most of the times, that's what is needed ;-) – Julio Nobre Dec 13 '18 at 11:38
7

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

Shell
  • 6,680
  • 10
  • 36
  • 70
  • 1
    Note: when using CD in a script, add the /D flag to allow drive switching as well as folder changing as, most of the time, it's the intended behaviour. – Chucky Mar 06 '20 at 09:52