function Remove-IdsFromFile {
param(
[Parameter(Mandatory=$true,Position=0)]
[string]$BigFile,
[Parameter(Mandatory=$true,Position=1)]
[Object[]]$IgnorePatterns
)
# Create the pattern matches
$regex = ($IgnorePatterns | ForEach-Object{[regex]::Escape($_)}) -join "|"
If(Test-Path $BigFile){
$reader = New-Object System.IO.StreamReader($BigFile)
$line=$reader.ReadLine()
while ($line -ne $null)
{
# Check if the line should be output to file
If($line -notmatch $regex){$line | Add-Content "CleansedBigFile.txt"}
# Attempt to read the next line.
$line=$reader.ReadLine()
}
$reader.close()
} Else {
Write-Error "Cannot locate: $BigFile"
}
}
StreamReader
是读取大型文本文件的首选方法之一。我们还使用正则表达式来构建要匹配的模式字符串。与我们使用的模式字符串[regex]::Escape()
如果存在正则表达式控制字符,请作为预防措施。必须猜测,因为我们只看到一个模式字符串。
If $IgnorePatterns
可以很容易地转换为字符串,这应该可以正常工作。一个小样本$regex
看起来会是:
XX000029|XX000028|XX000027
If $IgnorePatterns
从数据库填充,您对此的控制可能较少,但由于我们使用正则表达式,您可能可以通过以下方式减少该模式集实际使用正则表达式(而不仅仅是一个大的替代匹配)就像我上面的例子一样。你可以将其减少到XX00002[7-9]
例如。
我不知道正则表达式本身是否会提供 1500 种可能的性能提升。这StreamReader
这里应该是重点。然而我确实用了污染了水域Add-Content
到输出也没有因为速度快而获得任何奖励(could使用流编写器代替它)。
读者和作家
我仍然需要测试它以确保它有效,但这只是使用streamreader
and streamwriter
。如果它确实工作得更好,我将替换上面的代码。
function Remove-IdsFromFile {
param(
[Parameter(Mandatory=$true,Position=0)]
[string]$BigFile,
[Parameter(Mandatory=$true,Position=1)]
[Object[]]$IgnorePatterns
)
# Create the pattern matches
$regex = ($IgnorePatterns | ForEach-Object{[regex]::Escape($_)}) -join "|"
If(Test-Path $BigFile){
# Prepare the StreamReader
$reader = New-Object System.IO.StreamReader($BigFile)
#Prepare the StreamWriter
$writer = New-Object System.IO.StreamWriter("CleansedBigFile.txt")
$line=$reader.ReadLine()
while ($line -ne $null)
{
# Check if the line should be output to file
If($line -notmatch $regex){$writer.WriteLine($line)}
# Attempt to read the next line.
$line=$reader.ReadLine()
}
# Don't cross the streams!
$reader.Close()
$writer.Close()
} Else {
Write-Error "Cannot locate: $BigFile"
}
}
您可能需要对流进行一些错误预防,但它似乎确实可以正常工作。