regexcmdfindstr

Findstr - Return only a regex match


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?


Solution

  • The findstr tool cannot be used to extract matches only. It is much easier to use Powershell for this.

    Here is an example:

    $input_path = 'c:\ps\in.txt'
    $output_file = 'c:\ps\out.txt'
    $regex = '[0-9]+ errors'
    select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
    

    See How to use Regular Expressions in PowerShell? article on how to use the script above.