24

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
Mowgli
  • 3,422
  • 21
  • 64
  • 88
  • I think [this question](http://stackoverflow.com/questions/106053/how-can-i-make-a-batch-file-to-act-like-a-simple-grep-using-perl) has what you are looking for – zbrunson Nov 20 '12 at 15:49

2 Answers2

46

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.

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Hi, I have question hope you can help me, instead of log.txt, is there a way I can put URL it will only have one link of data. Thanks – Mowgli Nov 20 '12 at 18:34
  • Doesn't seem to work for me. (Hello World is never found) – Cestarian May 02 '16 at 01:16
  • @Cestarian - ???! I promise you both commands absolutely work fine. You either typed something wrong, or you are miss-applying the command. – dbenham May 02 '16 at 04:47
  • @dbenham yes it was my bad, I was reading the wrong output (stupid command prompt, I'm more used to bash shells). I'd remove the downvote I gave this if I could, says it's locked unless this is edited – Cestarian May 02 '16 at 12:50
4

Here is an alternative approach that also works. The code uses the findstr commmand to look inside the text file and find the specific string... returning an error level of 0 (if found) or an error level of 1 (if the string wasn't found).

findstr /m "Findme" Log.txt >Nul
if %errorlevel%==0 (
echo "Findme" was found within the Log.txt file!
)

if %errorlevel%==1 (
echo "Findme" wasn't found within the Log.txt file!
)
pause