我需要在将日志文件发送给供应商进行分析之前对其进行编辑。由于我支持的平台的动态特性,我必须动态生成列表。这一点还好。
例如我生成了一个大约有 500 行的 CSV 文件,如下所示:
"Node","Redaction"
"Server1","Redacted-Node-1"
"Server2.domain.local","Redacted-Node-2"
"Server3","Redacted-Node-3"
etc
我将此文件用作
$redactions = Import-Csv $nodeRedactions
脚本运行编辑文件以获取查找和替换对,然后对目标文件进行查找/替换。例如。 Server1 替换为 Redacted-Node-1。
$fullpath 是当前使用此代码处理的文本文件的路径:
$redactions = Import-Csv $nodeRedactions
$fileContent = Get-Content $fullpath
$n = 1
foreach ($row in $redactions)
{
#Write-Host $n + " " + $fullpath
$field1 = $row.Node
$field2 = $row.Redaction
$fileContent = $fileContent | Foreach-Object { $_ -replace $field1,$field2}
#$n= $n + 1
}
#Create the output file complete with redactions
$fileContent | Out-File $outputFile
这对于小文件非常有效。但是,当在具有 50,000 行的文件上运行时,对每行运行查找和替换大约需要 1 秒。有没有更快的方法?
我建议您使用哈希表在
Node
和 Redaction
值之间快速查找,并结合 正则表达式模式和使用此哈希表进行替换的匹配评估器。
$map = @{}
Import-Csv $nodeRedactions | ForEach-Object {
$map[$_.Node] = $_.Redaction
}
$re = [regex]::new(
'(?:{0})' -f ($map.Keys.ForEach({ [regex]::Escape($_) }) -join '|'),
[System.Text.RegularExpressions.RegexOptions] 'Compiled, IgnoreCase')
$content = Get-Content $fullPath -Raw
$re.Replace($content, { $map[$args[0].Value] }) | Set-Content $outputFile