【问题标题】:Iterating over multiple find and replace object迭代多个查找和替换对象
【发布时间】: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


【解决方案1】:

正如 cmets 中提到的 @AdminOfThings。问题是您正在读取文件一次,然后写入两次。因此,您最终不会像您期望的那样得到所有替代品。

见下文。我已经做了一些清理工作,但这是你可以做的......

我将文件的内容读入内存一次,并将其存储为变量。然后对变量进行替换,然后将变量的内容写入文件:

$inputTextFilePath = 'D:\StackOverflow\fart\test.txt'
$outputTextFilePath = 'D:\StackOverflow\fart\test_output.txt'

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

$fileContent = Get-Content $inputTextFilePath;

foreach ($item in $FindReplaceList)
{
    Write-Host "Replacing string $($item.FindString) to $($item.ReplaceString) where input file: $inputTextFilePath and output file: $outputTextFilePath";
    $fileContent = $fileContent.Replace($item.FindString, $item.ReplaceString);
}

Set-Content -Value $fileContent -Path $outputTextFilePath;

当然,因为“[F]ind [A]nd [R]eplace [T]ext”问题只是偶尔出现......我不得不使用那个花哨的首字母缩略词:)

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 2020-04-26
    • 2015-06-10
    • 2013-05-26
    • 2018-02-16
    • 1970-01-01
    • 2011-10-13
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多