How to find if a file contains a given string using Windows command line
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!
Related videos on Youtube
Jai
Updated on July 05, 2022Comments
-
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 over 5 yearsConsider adding /i switch in order to get case-insensitive comparison. Most of the times, that's what is needed ;-)
-
Chucky about 4 yearsNote: 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.