[英]Replace file text between two words across multiple lines
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 如果我想用
YYY
替换start
和end
之间的所有文本,结果文件应该是
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! 但是......没有运气!
As mentioned in the comments, you'll need to enable the s
modifier to have the .+?
如评论中所述,您需要启用
s
修饰符才能使用.+?
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)
作为安斯加尔提到
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
Or 要么
$file='C:\Path\to\file.txt'
$raw = (Get-Content $file -Raw) -ireplace '(?s)(?<=start).+?(?=end)', 'YYY'
$raw | Set-Content $file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.