Replace multiple lines of text with one line within a file

Hello All,

I have found how to accomplish this task in a few steps, however I’d like to think it’s possible to be more efficient than my multi-sourced findings. Here’s what I’m dealing with.

The file contains several lines of text, and I’m interested in two particular lines:


I’d like to take away both target lines of text and replace with a single line. Thanks for your help in advance!

Rather than replacing the two lines with a single line, I’ve chosen another route where I can remove one line, then replace the other line. If someone knows of a way to solve the original inquiry, it is welcome.

What I’m doing is -

c:\textfile.txt contains the following.


$var1 = “c:\textfile.txt” #sets the file in question to a variable
$var1gc = gc $var1 #sets the contents of the file to a variable
$deletetextvariable = ‘targettext2’ #sets the undesired text to a variable
$var1gc = $var1gc | where {$_ -ne $deletetextvariable} #re-sets an earlier defined variable by removing the undesired text (targettext2)
$var1gc | out-file $var1 -Force #updates the original file with the resulting content

I’m new to powershell, and welcome any input to make this more simple as the next step would be to replace the ‘targettext1’ with my desired text.



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:

Line 1 Line 2 Line 3 Line 4 Line 5

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'

# Output:

# Line 1
# Line 2
# This is a test.
# Line 5

@ Dave - Thanks! I have seen references to this before, however your associated explanations made this make sense!