Findstr - Return only a regex match

ohadinho picture ohadinho · Nov 24, 2016 · Viewed 15.1k times · Source

I have this string in a text file (test.txt):

BLA BLA BLA
BLA BLA
Found 11 errors and 7 warnings

I perform this command:

findstr /r "[0-9]+ errors" test.txt

In order to get just 11 errors string.

Instead, the output is:

Found 11 errors and 7 warnings

Can someone assist?

Answer

aschipfl picture aschipfl · Nov 24, 2016

findstr always returns every full line that contains a match, it is not capable of returning sub-strings only. Hence you need to do the sub-string extraction on your own. Anyway, there are some issues in your findstr command line, which I want to point out:

The string parameter of findstr actually defines multiple search strings separated by white-spaces, so one search string is [0-9]+ and the other one is error. The line Found 11 errors and 7 warnings in your text file is returned because of the word error only, the numeric part is not part of the match, because findstr does not support the + character (one or more occurrences of previous character or class), you need to change that part of the search string to [0-9][0-9]* to achieve that. To treat the whole string as one search string, you need to provide the /C option; since this defaults to literal search mode, you additionally need to add the /R option explicitly.

findstr /R /C:"[0-9][0-9]* errors" "test.txt"

Changing all this would however also match strings like x5 errorse; to avoid that you could use word boundaries like \< (beginning of word) and \> (end of word). (Alternatively you could also include a space on either side of the search string, so /C:" [0-9][0-9]* errors ", but this might cause trouble if the search string appears at the very beginning or end of the applicable line.)

So regarding all of the above, the corrected and improved command line looks like this:

findstr /R /C:"\<[0-9][0-9]* errors\>" "test.txt"

This will return the entire line containing a match:

Found 11 errors and 7 warnings

If you want to return such lines only and exclude lines like 2 errors are enough or 35 warnings but less than 3 errors, you could of course extend the search string accordingly:

findstr /R /C:"^Found [0-9][0-9]* errors and [0-9][0-9]* warnings$" "test.txt"

Anyway, to extract the portion 11 errors there are several options:

  1. a for /F loop could parse the output of findstr and extract certain tokens:

    for /F "tokens=2-3 delims= " %%E in ('
        findstr/R /C:"\<[0-9][0-9]* errors\>" "test.txt"
    ') do echo(%%E %%F
    
  2. the sub-string replacement syntax could also be used:

    for /F "delims=" %%L in ('
        findstr /R /C:"\<[0-9][0-9]* errors\>" "test.txt"
    ') do set "LINE=%%L"
    set "LINE=%LINE:* =%"
    set "LINE=%LINE: and =" & rem "%"
    echo(%LINE%