How do I return only the matching regular expression when I select-string(grep) in PowerShell? How do I return only the matching regular expression when I select-string(grep) in PowerShell? powershell powershell

How do I return only the matching regular expression when I select-string(grep) in PowerShell?


Or just:

Select-String .-.-. .\test.txt -All | Select Matches


David's on the right path. [regex] is a type accelerator for System.Text.RegularExpressions.Regex

[regex]$regex = '.-.-.'$regex.Matches('abc 1-2-3 abc') | foreach-object {$_.Value}$regex.Matches('abc 1-2-3 abc 4-5-6') | foreach-object {$_.Value}

You could wrap that in a function if that is too verbose.


I tried other approach: Select-String returns property Matches that can be used. To get all the matches, you have to specify -AllMatches. Otherwise it returns only the first one.

My test file content:

test test1 alk atest2 asdflkj alj test3 testtest test3 test4test2

The script:

select-string -Path c:\temp\select-string1.txt -Pattern 'test\d' -AllMatches | % { $_.Matches } | % { $_.Value }

returns

test1 #from line 1test2 #from line 1test3 #from line 1test3 #from line 2test4 #from line 2test2 #from line 3

Select-String at technet.microsoft.com