简体   繁体   English

在多行之间替换两个单词之间的文件文本

[英]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替换startend之间的所有文本,结果文件应该是

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.

相关问题 跨两个字符串之间的多行替换文本段 - 正则表达式 - Replace segment of text, across multiple lines between two strings - regex 替换两个单词之间的文字 - Replace text between two words awk在一个文件中两个单词之间的所有行出现多次 - awk all lines between two words in one file with multiple occurrences 使用正则表达式替换多行文本 - Using a Regex to Replace Text Across Multiple Lines preg_replace 替换两个符号之间多行的换行符 - preg_replace replace line breaks across multiple lines between two symbols 从powershell中的shell命令中提取两个关键字之间的多行文本 - Extract multiple lines of text between two key words from shell command in powershell Notepad ++替换产生多行的两个字符串之间的文本并在其间保留字符串的某些部分 - Notepad++ replace text between two strings spawning multiple lines and retain some part of the string in between 比较两个文本文件并替换Powershell中包含常用词的行 - Compare two text files and replace the lines containing common words in powershell 使用正则表达式替换文本文件中特定的两个文本行之间的内容 - Replace the content between specific two text lines in a text file using regular expression 使用正则表达式替换文件中的多行文本 - Using Regex to replace multiple lines of text in file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM