views:

44

answers:

1

I have lots of text output from a tool that I want to parse in Powershell 2.0. The output is nicely formatted so I can construct a regex to pull out the data I want using select-string. However getting the subsequent matches out of select-string seems long-winded. There has to be a shorter way?

This works:

p4 users | select-string "^\w+(.\w+)?" | 
    select -Expand Matches | %{p4 changes -u $_.Value}

But All those Matches and Values are verbose. There's nothing obvious in the select-string help file, but is there a way to make it pump out just the regex matches as strings? A bit like:

p4 users | select-string "^\w(.\w+)?" -ImaginaryMagicOption | %{p4 changes -u $_}
+1  A: 

In this case, it may be a bit easier to use -match e.g.:

p4 users | Foreach {if ($_ -match '^\w+(.\w+)?') { p4 changes -u $matches[0] }}

This is only because the output of Select-String is MatchInfo object that buries the Matches info one level down. OTOH it can be made to work:

p4 users | Select-String "^\w+(.\w+)?" | 
    Foreach {p4 changes -u $_.Matches[0].Value}
Keith Hill
In your first snippet, I actually want `$matches[0]` but otherwise that's awesome. cheers.
tenpn
I assumed you wanted just the group capture `(.\w+)` but if $matches[0] works for you that's cool. I've updated the answer to reflect that.
Keith Hill