powershell - 如何更快地过滤带有某些字符的文件行?

标签 powershell powershell-4.0

所以我整理了一些很大的平面文件。

我正在尝试使用PowerShell做的是仅选择具有预期分隔符数量的行,并将其输出到文件中。

这有效:

function fixColDelim([string]$importFile)
{
$goodFile = $importFile.Replace(".txt", "_GOODX1.txt")

$sr = New-Object -TypeName System.IO.StreamReader -ArgumentList $importFile
$sw = New-Object -TypeName System.IO.StreamWriter -ArgumentList $goodFile

$sr.ReadLine() | Out-Null
$sr.ReadLine() | Out-Null

While (-not $sr.EndOfStream) {
    $line = $sr.ReadLine().ToString()
    $gl = ($line.ToCharArray() | Where-Object {$_ -eq '|'} | Measure-Object).Count
    Write-Host $gl
    if($gl -eq 350)
    {
        $sw.WriteLine($sr.ReadLine())
    }
}
$sw.close()
$sr.close()
}

但是,它是RBAR,因此它不是处理500mb文件的最有效方法。有什么建议么?

扎克

最佳答案

这是替换正则表达式的替代方法。

$gl = ($line -replace '[^|]','').length

如果您可能嵌套了定界符,则可以更进一步。
$gl = ($line -replace '[^|"]','' -replace '"\|"',"").length

关于powershell - 如何更快地过滤带有某些字符的文件行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43285580/

相关文章:

PowerShell 流输出

powershell - 查找并替换同时包含双引号和方括号的字符串

c++ - 通过 Powershell 远程 session 执行时程序输出不同

powershell - Powershell将文件路径中最后出现的 '/'替换为 '.'

credentials - 存储用于以管理员身份运行 PowerShell 的凭据

PowerShell Out-file -width 在导出到文件时不会截断内容

windows - 我可以让这个脚本更快吗?

powershell - 尝试在 heroku 上部署 Strapi 时出错。 grep 和 cut 无法识别

function - Powershell-即使不满足条件,函数中的if语句也仅使用第一个

powershell - 如何使用通用脚本语言从内置扬声器发出 BIOS 蜂鸣声?