我有以下 PowerShell 脚本:
$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" }
这似乎没有替换文本。是多行字符串的问题,还是Replace()方法的限制?我希望能够在不使用正则表达式的情况下进行替换。
-Raw
开关是Powershell v3的一个不错的补充。在v2中,我经常依赖于Get-Content <file> | Out-String
来实现类似的结果。在这个答案中有更多细节相关的问题。 - ajk(Get-Content -raw file.txt) -replace $oldCode, $newCode | Set-Content file.txt
- Henrik