It can be done with regular expressions in multiline mode (if you read the entire contents of your file into a single string, rather than an array of strings), but it’s not at all easy to read. Here’s some code I ran on my computer as a test (using PowerShell v3). I created a file called “test.txt” with the following contents:
Then ran these commands at the console:
# The -Raw switch in PowerShell v3 reads the file as a single string (including the line-ending characters) instead of an array.
$text = Get-Content '.\test.txt' -Raw
# The (?m) at the beginning of the regex pattern puts it into multiline mode, so the ^ anchor
# will match the beginning of a line, instead of the beginning of the entire file. Multiline
# mode is supposed to also make the $ anchor match the end of any line, but that wasn't working
# in my tests, for some reason. Not sure why.
$text -replace '(?m)(.*)^Line 3[\r\n]+Line 4([\r\n]+.*)', '$1This is a test.$2'
# Line 1
# Line 2
# This is a test.
# Line 5