SureThing
SureThing

Reputation: 97

Using Regex to replace multiple lines of text in file

Basically, I have a .bas file that I am looking to update. Basically the script requires some manual configuration and I don't want my team to need to reconfigure the script every time they run it. What I would like to do is have a tag like this

<BEGINREPLACEMENT>
'MsgBox ("Loaded")


ReDim Preserve STIGArray(i - 1)
ReDim Preserve SVID(i - 1)

STIGArray = RemoveDupes(STIGArray)
SVID = RemoveDupes(SVID)
<ENDREPLACEMENT>

I am kind of familiar with powershell so what I was trying to do is to do is create an update file and to replace what is in between the tags with the update. What I was trying to do is:

$temp = Get-Content C:\Temp\file.bas
$update = Get-Content C:\Temp\update
$regex = "<BEGINREPLACEMENT>(.*?)<ENDREPLACEMENT>"

$temp -replace $regex, $update
$temp | Out-File C:\Temp\file.bas

The issue is that it isn't replacing the block of text. I can get it to replace either or but I can't get it to pull in everything in between.

Does anyone have any thoughts as to how I can do this?

Upvotes: 1

Views: 128

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You need to make sure you read the whole files in with newlines, which is possible with the -Raw option passed to Get-Content.

Then, . does not match a newline char by default, hence you need to use a (?s) inline DOTALL (or "singleline") option.

Also, if your dynamic content contains something like $2 you may get an exception since this is a backreference to Group 2 that is missing from your pattern. You need to process the replacement string by doubling each $ in it.

$temp = Get-Content C:\Temp\file.bas -Raw
$update = Get-Content C:\Temp\update -Raw
$regex = "(?s)<BEGINREPLACEMENT>.*?<ENDREPLACEMENT>"
$temp -replace $regex, $update.Replace('$', '$$')

Upvotes: 1

Related Questions