Search code examples
regexbatch-filegrepfindstr

Equivalent of `grep -o` for findstr command in Windows


In Unix, the command grep -o prints out only the matched string. This is very helpful when you are searching for a pattern using regular expression and only interested in what matched exactly and not the entire line.

However, I'm not able to find something similar for the Windows command findstr. Is there any substitute for printing only matched string in windows?

For example:

grep -o "10\.[0-9]+\.[0-9]+\.[0-9]+" myfile.txt

The above command prints only the IP address in myfile.txt of the form 10.*.*.* but not the entire lines which contain such IP adresses.


Solution

  • PowerShell:

    select-string '10\.[0-9]+\.[0-9]+\.[0-9]+' myfile.txt | foreach-object {
       $_.Matches[0].Groups[0].Value
    }