如何使用 Powershell 中的 StreamReader 类来查找和计算文件中包含的字符数?

gsh*_*ong 4 powershell

我是 powershell 的新手,对 .net 没有经验。我有一个脚本,用于
(get-content | select-string -pattern -allmatches).matches | measure-object
查找和计算文件中的字符数。如果文件只包含少于 10k 行,我的脚本将正常工作。否则对于大文件,RAM 将达到 100%,然后 Powershell 将显示(无响应)

我做了一些研究,发现 system.io.streamreader 可以工作,我在 Stackoverflow 中阅读了几个问题,要查找和匹配文件中的字符或单词,您只需执行以下操作:

$file = get-item '<file path>'

$reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $file

[int]$line = 0

while ( $read = $reader.ReadLine() ) {

    if ( $read -match '<charcter>' ) {

        $line++

    }

}
Run Code Online (Sandbox Code Playgroud)

但这只是返回包含字符的行数,而不是文件中的字符数。那么我如何使用(select-string -inputobject -pattern -allmatches).matches | measure-object流阅读器呢?

Sea*_*ean 7

您可以使用ToCharArraywhere来查找匹配项。例如,要计算文件中“e”的数量,您可以说:

$file = get-item '<file path>'

$reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $file

[int]$count = 0

while ( $read = $reader.ReadLine() ) {

    $matches = ($read.ToCharArray() | where {$_ -eq 'e'}).Count
    $count = $count + $matches
}
Run Code Online (Sandbox Code Playgroud)