0

Is there anything which gets the lines of given pattern in python like we have in powershell

$Response2.RawContent -split "`n" | Select-String $ans -Context 1,4

in powershell it is getting 1 line before and 4 lines after the line in which matched string found.

I'm new to python, worked more on powershell. Kindly help me on this.

phuclv
  • 37,963
  • 15
  • 156
  • 475

1 Answers1

0

If you mean the surrounding context lines, there's some stuff in the return object to help you (via .NET).

Each result of Select-String will have it's .Matches property. This is an array of [System.Text.RegularExpression.Match[]].

Each match will have various properties and methods. .Result() is incredibly useful, but unintuitively named. It allows you to perform a substition on the result. This document describes all of the substitutions you can make. I'll draw your attention to two: $` and $',

$Response2.RawContent -split "`n" | Select-String $ans | Select-Object -ExpandProperty Matches | Foreach-Object {
    $allTextBefore = $_.Result("$`")
    $allTextAfter  = $_.Result("$'")

}

In case the names of the variables above do not make it clear, those variables will contain all the text before and after the result.

If you wanted to go back N number of lines, you could:

  1. Use -split to break each result into a number of lines -split '(?>\r\n|\n)'
  2. Use negative indexing to get the last N lines, i.e. $lines[-4..-1]
Start-Automating
  • 8,067
  • 2
  • 28
  • 47