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

3

19

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?

Vitreous answered 11/4, 2011 at 20:4 Comment(0)
H
20

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 )
Hooker answered 15/8, 2013 at 14:17 Comment(1)
Consider adding /i switch in order to get case-insensitive comparison. Most of the times, that's what is needed ;-)Transilluminate
M
9

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!

Methoxychlor answered 25/3, 2014 at 2:9 Comment(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.Reggy
S
0

Another solution:

type "file.txt" | findstr "searchString" >nul

if %ERRORLEVEL% equ 0 (
    echo found it!
) else (
    echo not found
)
Skiascope answered 27/6 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.