views:

202

answers:

2

In PowerShell I find myself doing this kind of thing over and over again for matches:

some-command | select-string '^(//[^#]*)' |
     %{some-other-command $_.matches[0].groups[1].value}

So basically - run a command that generates lines of text, and for each line I want to run a command on a regex capture inside the line (if it matches). Seems really simple. The above works, but is there a shorter way to pull out those regex capture groups? Perl had $1 and so on, if I remember right. Posh has to have something similar, right? I've seen "$matches" references on SO but can't figure out what makes that get set.

I'm very new to PowerShell btw, just started learning.

+2  A: 

You can use the -match operator to reformulate your command as:

some-command | Foreach-Object { if($_ -match '^(//[^#]*)') { some-other-command $($matches[1])}}
Bas Bossink
Eh? He's matching a line that starts with double-slash (//) and greedily matching up until (but excluding) the first hash (#). There is no end-of-line marker, so he's not specifically matching the entire line.
Peter Boughton
Yeah, that's the kind of thing I was looking for. Thanks for the edit, Bas.
Scott Bilas
+1  A: 

You could try this:

Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value }
Shay Levy