views:

1581

answers:

5

Hello,

I trying to find a pattern in files, but i when i get a match using select-string, i don't want the entire line, i just want the part that matched. Is there a parameter i can specify to do this?

Ex:

If i did

select-string .-.-.

and the file contained a line with: abc 1-2-3 abc

I'd like to get a result of just "1-2-3" instead of the entire line getting returned.

I believe in unix what i want is grep -o, but i haven't found an equivalent in powershell and googling anything with a dash doesn't work well.

Does anyone know a good method of getting this result?

+1  A: 

You can use the System.Text.RegularExpressions namespace:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

David McEwing
+4  A: 

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.

Steven Murawski
Thanks this worked perfectly!
Skyler
+2  A: 

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 test
test test3 test4
test2

The script:

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

returns

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

Select-String at technet.microsoft.com

stej
I couldn't get this one working, i only have access to PS 1.0 and it doesn't look like -AllMatches is recognized in 1.0 at least. Thanks anyways!
Skyler
Hmm, I work with v2, ctp3. I have no possibility to try to solve that on v1, so sorry..
stej
Support for matches was added in v2, in addition to context.
JasonMArcher
+2  A: 

in the spirit of "teach a man to fish" ...

What you want to do is pipe the output of your select-string command into Get-member, so you can see what properties the objects have. Once you do that, you'll see "Matches" and you can select just that by piping your output to | Select-Object Matches

My suggestion is to use something like: select linenumber, filename, matches

eg: on stej's sample:

sls .\test.txt -patt 'test\d' -All |select lineNumber,fileName,matches |ft -auto

LineNumber Filename Matches
---------- -------- -------
         1 test.txt {test1, test2, test3}
         2 test.txt {test3, test4}
         3 test.txt {test2}
Jaykul
+2  A: 

Or just:

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