Could anyone assist me in finding a simple way to find a string in a text file then deleting 10 lines above that matched text using powershell?
For instance, I have a text file along these lines (with multiple instances of similar text I want to find):
=============start============
random text
random text
random text
random text
random text
string I want to find
=============end============
=============start============
random text
random text
random text
=============end============
=============start============
random text
random text
random text
=============end============
=============start============
random text
random text
random text
=============end============
=============start============
random text
random text
random text
=============end============
So in this example, I want to search for every instance of "String I want to find" and when found delete the X lines above the matched text, outputting the rest to another .txt file. The number of lines above is always the same.
I have tried to match the text between the two strings as follows:
(Get-Content -LiteralPath $Path\processing\data.txt) -replace '$matchstart*$matchend','' |out-file $Path\processing\test.txt
However, this doesn't seem to give me the output I was hoping for (doesn't remove anything).
This also works, but potentially will cause issues because the start string often appears multiple times and could lead to me deleting more than I want to.
$str = Get-Content $Path\processing\pfxdetailpre.txt | out-string
$start = $str.indexOf($nokeystart) + 1
$end = $str.indexOf($nokeyend, $start)
$length = $end - $start
$result = $str.substring($start, $length)
The following seems to work great to delete my string and the line before. I can't figure out how to edit it to delete X more lines above though.
gc $file | %{
$a=$b=$null
}{
if($a){$a}
$a=$b
$b=$_
if($b -match $key){$a=$b=$null}
}{
if($b -notmatch $key){
if($a){if($b){"$a`n$b"}else{$a}}elseif($b){$b}
}
} | out-file $newfile