给定一个文本文件,我想替换两个给定单词之间的所有文本(跨多行)。
文本文件示例:
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
但是……运气不好!
最佳答案
如评论中所述,您需要启用 s
修饰符有 .+?
部分也匹配换行符。
正如 Ansgar 提到的 m
在这里不是必需的,但可以增强 start
通过锚定在以 (?<=^xstart)
开头的行
$file='C:\Path\to\file.txt'
$raw = Get-Content $file -Raw
$raw = $raw -ireplace '(?s)(?<=start).+?(?=end)', 'YYY'
$raw | Set-Content $file
或者
$file='C:\Path\to\file.txt'
$raw = (Get-Content $file -Raw) -ireplace '(?s)(?<=start).+?(?=end)', 'YYY'
$raw | Set-Content $file
关于regex - 跨多行替换两个单词之间的文件文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048319/