1

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"

3 Answers 3

3

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])
}
Sign up to request clarification or add additional context in comments.

Comments

2

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}

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.