Reputation: 30138
I use select-string from powershell and it works nice, but sometimes I dont like that it gives me the entire line that matched because it contains (for me) unnecessary information.
Is there simple way to have it give me just 10 chars before regex, regex and 15 chars after? example of how I use it now:
gci *.log | select-string "lastname"
Upvotes: 1
Views: 5093
Reputation: 2166
Remember you always get pipe objects to Get-Member
to see properties.
PS C:\> $text = 'asdfqwerasdfqwerlastnameasdfqwerasdfqwerasdf'
PS C:\> $text | Select-String -Pattern 'lastname' | Get-Member
Name MemberType Definition
---- ---------- ----------
...
Matches Property System.Text.RegularExpressions.Match[] Matches {get;set;}
PS C:\> ($text | Select-String -Pattern 'lastname').Matches
Groups : {lastname}
Success : True
Captures : {lastname}
Index : 16
Length : 8
Value : lastname
PS C:\> $index = ($text | Select-String -Pattern 'lastname').Matches.Index
PS C:\> $text[($index-10)..($index+15)] -join ''
erasdfqwerlastnameasdfqwer
Upvotes: 2
Reputation: 200503
Make the regexp (.{10})lastname(.{15})
and use Where-Object
with the -match
operator instead of Select-String
:
gci *.log | ? { $_ -match '(.{10})lastname(.{15})' } | % {
"{0}`t{1}" -f ($matches[1], $matches[2])
}
Upvotes: 3
Reputation: 3429
You'll need to use groups, you can use named groups like this:
gci c:\temp\_sotemp\*.log |
select-string -Pattern "(?<refvalue>lastname)" |
select -expand Matches |
foreach {$_.groups["refvalue"].value}
Upvotes: 2