简体   繁体   中英

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

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 .+? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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