Check if a particular text is present in multiple files using batch command file.

Sometimes we need to check if a particular text is present in one or many files. Let us say for example, we have text files containing employee details for different years. Now we have to check if a particular employee number (say 1234) is present in each file or not. This is a time-consuming process if done manually, and more so if we have many text files with us.
We can do this very easily using the below batch command method.
1. Copy all the files to be searched into one folder.
2. In the same folder create a batch command file searchtext.cmd (file with .cmd extension) using notepad.
3. Copy the below batch commands into the searchtext.cmd file and save.
@echo off
SET RESULT_FILE="result.txt"
SET /p "var1=Enter the String to Search: "
pushd %~p0
type NUL > %RESULT_FILE%.tmp
FOR /f "delims=" %%a in ('dir /B /S *.txt') do (
FOR /f "tokens=3 delims=:" %%c in ('find /i /c "%var1%" "%%a"') do (
FOR /f "tokens=*" %%f in ('find /i "%var1%" "%%a"') do if %%c neq 0 echo %%f
) >> "%RESULT_FILE%".tmp
move %RESULT_FILE%.tmp %RESULT_FILE% >nul 2>&1
:: Open the file

4. Run the searchtext.cmd file (Double click).
5. It opens a command prompt requesting you to enter the search string. Enter the string that you want to search and press Enter.
6. It will process, and gives the search results in a new text file result.txt.
Above code can be used for text files (.txt). If we need to search for a text in a file with any other extension say xml file (.xml), we need to change the extension in the first for loop.
FOR /f “delims=” %%a in (‘dir /B /S *.xml’) do (


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s