简体   繁体   English

使用正则表达式替换文件中的多行文本

[英]Using Regex to replace multiple lines of text in file

Basically, I have a .bas file that I am looking to update.基本上,我有一个要更新的 .bas 文件。 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.我对powershell有点熟悉,所以我想做的是创建一个更新文件并用更新替换标签之间的内容。 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?有没有人对我如何做到这一点有任何想法?

You need to make sure you read the whole files in with newlines, which is possible with the -Raw option passed to Get-Content .您需要确保使用换行符读取整个文件,这可以通过将-Raw选项传递给Get-Content

Then, .然后, . does not match a newline char by default, hence you need to use a (?s) inline DOTALL (or "singleline") option.默认情况下不匹配换行符,因此您需要使用(?s)内联 DOTALL(或“单行”)选项。

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.此外,如果您的动态内容包含类似$2您可能会收到一个异常,因为这是对您的模式中缺少的组 2 的反向引用。 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('$', '$$')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM