Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 584
Jai Avatar asked Apr 11 '11 20:04

Jai


People also ask

How do I search for a text string in DOS?

Using the findstr command lets you search for text within any plaintext file. Using this command within a batch file lets you search for text and create events off the results found.

How do I search for a string in a file?

Use the grep command to search the specified file for the pattern specified by the Pattern parameter and writes each matching line to standard output. This displays all lines in the pgm. s file that begin with a letter.


1 Answers

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 )
like image 149
Mike Q Avatar answered Oct 10 '22 23:10

Mike Q