使用Powershell脚本替换给定输入中文本的第一个出现

时间:2013-04-18 03:41:58

标签: replace powershell-v3.0

以下代码有效,但它会替换它找到的所有文本。有没有办法只替换第一次出现。我已经尝试了4天了。

请帮忙。

cls   
$fileName = "c:\test\bmsbackuplog.htm"  
$findstring=Select-string $fileName -Pattern "The backup of volume system reserved" -list 
$replacement = "<tr><td>Change using this line</td></tr>"    
$firstdata=$findstring[0].Line 
$both="$firstdata$replacement"  
$match ="The backup of volume system reserved*.*"  
(Get-Content ($fileName)) -replace $match,$both | Set-Content "c:\test\bmsbackuplog.htm"

1 个答案:

答案 0 :(得分:0)

我会使用零宽度负向外观断言:

$fileName = "c:\test\bmsbackuplog.htm"
$pattern = 'The backup of volume system reserved'
$replacement = '$1<tr><td>Change using this line</td></tr>' 
[io.file]::ReadAllText($fileName) -replace "(?<!$pattern[\s\S]*)($pattern)", $replacement