views:

6584

answers:

3

I want to write a batch script that should read a text file line by line and search for a keyword.

If the keyword is found it should return value 0 else it should return 1. Like this it should keep on incrementing the value until the end of the file. The output should go to a file.

The sample log is as follows,

Website is available HTTP/1.1 200 OK
Website is available HTTP/1.1 200 OK
Website is available HTTP/1.1 200 OK
Website is available HTTP/1.1 200 OK
Website is available HTTP/1.1 200 OK
Website is available HTTP/1.1 200 OK

Basically I want to count the number of times the website failed. So, if the website is ok, then it should return value '0' if it is not then value '1'.

Last but not least I want the total number of times the website failed.

+2  A: 

On Unix

fgrep 'keyword' log.txt | wc -l
antti.huima
Shorter: fgrep -c 'keyword' log.txt
Thomas
+3  A: 

For Windows .bat:

FINDSTR /V /B /C:"HTTP/1.1 2" log.txt

will list every line that did not (/V) start with (/B) the literal (/C:) string "HTTP/1.1 2".

Since HTTP success codes are in the 200 block (eg, 203 for cache hit), this will only list non-success responses. FINDSTR does have some regex support, but it is pretty weak, (no grouping or alternation, especially), so if you want to filter out multiple response codes using FINDSTR you would have to chain them, eg to also filter out Auth failures:

FINDSTR /V /B /C:"HTTP/1.1 2" log.txt | FINDSTR /V /B /C:"HTTP/1.1 403"
Simon Buchan
A: 

On DOS it would be the following line. Replace "FAIL STRING" with whatever a line will contain when the server has died.

FIND /C "FAIL STRING" log.txt

This outputs something like the following when there are two lines containing "FAIL STRING"

---------- LOG.TXT: 2

You can also use %ERRORLEVEL% to determine if there were any failures. Like this:

FIND /C "FAIL STRING" log.txt
IF ERRORLEVEL 1 ECHO Everything is A-OK
IF NOT ERRORLEVEL 1 ECHO There were failures

Good Luck,
Randy

Randy Stegbauer
Be careful with ERRORLEVEL, it is not a real envvar, IF and %% have special support. So if you SET ERRORLEVEL=1, then later exits will not change it.
Simon Buchan