tenpn
tenpn

Reputation: 4706

Concisely parsing a pipe

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 $_}

Upvotes: 1

Views: 832

Answers (1)

Keith Hill
Keith Hill

Reputation: 201602

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}

Upvotes: 2

Related Questions