Pergunta

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"
Foi útil?

Solução

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])
}

Outras dicas

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}

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top