How to find if a file contains a given string using Windows command line

132,426

Solution 1

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 )

Solution 2

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!

Share:
132,426

Related videos on Youtube

Jai
Author by

Jai

Updated on July 05, 2022

Comments

  • Jai
    Jai almost 2 years

    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?

  • Julio Nobre
    Julio Nobre over 5 years
    Consider adding /i switch in order to get case-insensitive comparison. Most of the times, that's what is needed ;-)
  • Chucky
    Chucky about 4 years
    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.

Related