Powershell Extended Regular Expression to Select from File

I would like to find a template in a file that I can do easily with something like:

  gc $ filename |  select-string $ pattern

However, as soon as I found this first pattern using the location (string) of the first match as a starting point, I would like to start searching for the second pattern. Once the second pattern is matched, I would like to return all the lines between the first and second matches, discarding the corresponding lines themselves.

+4
source share
5 answers

Say your first pattern is pattern1 and your second pattern is pattern2

then the expression will be (?<=pattern1)(.*?)(?=pattern2)

(?<=pattern1) - this will match the prefix pattern, but exclude it from capture
(?=pattern2) - this will match the suffix pattern, but exclude it from capture

+2
source

There may be a more elegant way, but it will work

 function ParseFile { param([string] $FileName) $s = gc $FileName; for($x = 0 ; $X -lt $s.count; $x++) { if(-not $first ){ if($s[$x] -match "1000"){ $first =$x } } else{ if($s[$x] -match "1075"){ $second = $x ; break; } } } (($first +1) .. ($second -1))|%{ $ret += $s[$_] } return $ret; } 
+1
source

I used foreach with $foreach.Movenext() :

 foreach ($line in (Get-Content $file)) { if ($line -match $firstTag) { do { $line $foreach.MoveNext() } until ($foreach.current -match $secondTag) continue } } 

This will just return each row one by one, but you can do what you like in the do-loop if you need to handle the result somehow.

+1
source

Here is my (French bricolage; o)), imagine the file c: \ temp \ gorille.txt:

 C'est à travers de larges grilles, Que les femelles du canton, Contemplaient un puissant gorille, Sans souci du qu'en-dira-t-on. Avec impudeur, ces commères Lorgnaient même un endroit précis Que, rigoureusement ma mère M'a défendu de nommer ici... Gare au gorille !... 

Here is the text between "canton" and "endroit"

 PS > (((Get-Content -Path C:\temp\gorille.txt) -join "£" | Select-String -Pattern "(?=canton)(.*)(?<=endroit)").matches[0].groups[0].value) -split "£" canton, Contemplaient un puissant gorille, Sans souci du qu'en-dira-t-on. Avec impudeur, ces commères Lorgnaient même un endroit 

I join all the lines with the special character "E" (select onather one if used), then use the @Alex Aza pattern in CmdLet Select-String , then split again.

+1
source
 $start = select-string -Path $path -pattern $pattern1 -list | select -expand linenumber $end = select-string -path $path -pattern $pattern2 | where-object {$_.linenumber -gt $start} | sort linenumber -desc | select -first 1 -expand linenumber (get-content $path)[$start..($end -2)] 
0
source

All Articles