在不使用正则表达式的情况下使用 Powershell 替换文件中的多行文本 [英] Replace multiline text in a file using Powershell without using Regex
问题描述
我有以下 Powershell 脚本:
$oldCode = @"<div id="time_estimate"><!-- 一些大桌子-->
"@$newCode = @"<div id="time_estimate"><!-- 嵌套的 div 和 spans --><div id="联系表单"><?php 包含 "contact-form.php";?>
"@ls *.html |foreach{$fileContent = [System.Io.File]::ReadAllText($_.FullName)$newFileContent = $fileContent.Replace($oldCode, $newCode)[System.Io.File]::WriteAllText($_.FullName, $newFileContent)写主机`r`n"写主机已处理 - $($_.Name)...`r`n"}
这似乎并没有取代文本.这是多行字符串的问题,还是 Replace() 方法的限制?我宁愿在不引入正则表达式的情况下进行替换.
您使用的是哪个版本的 PowerShell?如果您使用的是 v3 或更高版本,请尝试以下操作:
ls *.html |foreach{$fileContent = Get-Content $_.FullName -Raw$newFileContent = $fileContent -replace $oldCode, $newCodeSet-Content -Path $_.FullName -Value $newFileContent写主机`r`n"写入主机已处理 - $($_.Name)...`r`n"}
I have the following Powershell script:
$oldCode = @"
<div id="time_estimate">
<!-- some large table -->
</div>
"@
$newCode = @"
<div id="time_estimate">
<!-- nested divs and spans -->
<div id="contact-form">
<?php include "contact-form.php"; ?>
</div>
</div>
"@
ls *.html | foreach {
$fileContent = [System.Io.File]::ReadAllText($_.FullName)
$newFileContent = $fileContent.Replace($oldCode, $newCode)
[System.Io.File]::WriteAllText($_.FullName, $newFileContent)
Write-Host "`r`n"
Write-Host "Processed - $($_.Name)...`r`n" }
This doesn't seem to be replacing the text. Is it an issue with the multiline strings, or the limits of the Replace() method? I would prefer to do the replace without bringing in regex.
What version of PowerShell are you using? If you're using v3 or higher, try this:
ls *.html | foreach {
$fileContent = Get-Content $_.FullName -Raw
$newFileContent = $fileContent -replace $oldCode, $newCode
Set-Content -Path $_.FullName -Value $newFileContent
Write-Host "`r`n"
Write-Host "Processed - $($_.Name)...`r`n"
}
这篇关于在不使用正则表达式的情况下使用 Powershell 替换文件中的多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!