Reputation: 331
Given a text file I want to replace all the text (across multiple lines) between two given words.
Text file example:
line1 line2 XstartX line4 XendX line5
if I wanted to replace all the text between start
and end
with YYY
the resulting file should be
line1 line2 XstartYYYendX line5
I tried
$file='C:\Path\to\file.txt'
$raw = Get-Content $file -Raw
$raw -ireplace '(?<=start).+?(?=end)', 'YYY'
$raw | Set-Content $file
but... no luck!
Upvotes: 3
Views: 193
Reputation:
As mentioned in the comments, you'll need to enable the s
modifier to have the .+?
part also match line breaks.
As Ansgar mentions the m
isn't neccessary here, but could enhance the start
by anchoring at line begin with (?<=^xstart)
$file='C:\Path\to\file.txt'
$raw = Get-Content $file -Raw
$raw = $raw -ireplace '(?s)(?<=start).+?(?=end)', 'YYY'
$raw | Set-Content $file
Or
$file='C:\Path\to\file.txt'
$raw = (Get-Content $file -Raw) -ireplace '(?s)(?<=start).+?(?=end)', 'YYY'
$raw | Set-Content $file
Upvotes: 1