【发布时间】:2020-12-22 09:31:11
【问题描述】:
我知道下面的解决方案非常简单,但我无法让它工作。我创建了一个带有查找和替换字符串属性的对象。目标是替换文本文件中的所有字符串,但它不能正常工作。下面的代码只会替换列表中的最后一个对象。我搜索了几个 stack over flow 问题,但只能找到多个文件,而不是多个查找/替换字符串。
输入文件: 温度 1 温度 2 平均 1 平均 2
预期输出: 温度 1 温度 2 平均 1 平均 2
实际输出: 温度 1 温度 2 平均 1 平均 2
class FindReplace {
[string]$FindString;
[string]$ReplaceString;
}
[System.Collections.Generic.List[FindReplace]]$FindReplaceList = @()
$Obj1 = New-Object FindReplace
$Obj1.FindString = "AVERAGE"
$Obj1.ReplaceString = "AVG"
$Obj2 = New-Object FindReplace
$Obj2.FindString = "TEMPERATURE"
$Obj2.ReplaceString = "TEMP"
$FindReplaceList.Add($Obj1);
$FindReplaceList.Add($Obj2);
write-host $FindReplaceList.Count
for($i = 0; $i -lt $FindReplaceList.Count; $i++)
{
Write-Host "Replacing string" $FindReplaceList[$i].FindString "to" $FindReplaceList[$i].ReplaceString " where input file:" $inputTextFilePath "and output file:" $outputTextFilePath
(Get-Content $inputTextFilePath).Replace($FindReplaceList[$i].FindString, $FindReplaceList[$i].ReplaceString) | Set-Content $outputTextFilePath
}
【问题讨论】:
-
输入输出文件是同一个文件吗?如果没有,您将永远不会使用后续替换重新阅读更新
-
啊,好吧!谢谢你的快速反应。我忽略了它!
标签: powershell