Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if text file contain certain text in batch?

Tags:

batch-file

I have text file in same folder as where my batch file is.

so I want my batch file to read content of the text file and depending on content of that text file I want it to perform action.

example if text file contains "Hello World" then do like Start VLC if it doesn't contain Hello World then do something else.

Text will update on it's own.

here is my batch code so far, it can output the text from text file on screen.

@echo off
for /f "tokens=*" %%a in (log.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof
like image 859
Mowgli Avatar asked Nov 20 '12 15:11

Mowgli


People also ask

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

How do I search for a word in a batch file?

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.


1 Answers

You should use either FIND or FINDSTR. Type HELP FIND and HELP FINDSTR from a command prompt to get documentation. FIND is very simple and reliable. FINDSTR is much more powerful, but also tempermental. See What are the undocumented features and limitations of the Windows FINDSTR command? for more info.

You don't care about the output of either command, so you can redirect output to nul.

Both commands set ERRORLEVEL to 0 if the string is found, and 1 if the string is not found. You can use the && and || operators to conditionally execute code depending on whether the string was found.

>nul find "Hello World" log.txt && (
  echo "Hello World" was found.
) || (
  echo "Hello World" was NOT found.
)

>nul findstr /c:"Hello World" log.txt && (
  echo "Hello World" was found.
) || (
  echo "Hello World" was NOT found.
)

You could also test ERRORLEVEL in an IF statement, but I prefer the syntax above.

like image 200
dbenham Avatar answered Oct 12 '22 23:10

dbenham