Search code examples
windowsbatch-filecmdfindfindstr

How to count the occurrence of a variable in log file matching a pattern/RegEx in windows batch script


I'm trying to store number occurrence of a value to count variable.

set ATTR_TO_VERIFY=W10SBRS
for /F "tokens=*" %%N  in ('findstr /r "^<.*^>.*%ATTR_TO_VERIFY%.*:" lofile.log ^| find /v "" /c') do set "COUNT=%%N"
echo %COUNT%

but count always give me value zero.


Solution

  • The regex error that @MCDN pointed out in the comments is the one causing the trouble.
    You can also do it without the find /c. To count the number of lines in the result of your findstr command the following should do:

    set ATTR_TO_VERIFY=W10SBRS
    for /F "tokens=*" %%N in ('findstr /n /r "<.*>.*%ATTR_TO_VERIFY%.*:" lofile.log') do set /a COUNT+=1
    echo %COUNT%
    

    The FOR /F automatically discards empty lines and lines starting with a ; though. A way to solve this is to add the /n flag to the findstr and let findstr add the line numbers at the beginning of each matched line.