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

时间:2017-05-24 13:38:02

标签: 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++

    }

}

但这只返回包含该字符的行数,但不返回文件中的字符数。那么如何将(select-string -inputobject -pattern -allmatches).matches | measure-object与streamreader一起使用?

1 个答案:

答案 0 :(得分:3)

您可以使用ToCharArraywhere查找匹配项。例如,要计算&#34; e&#34;你可以在文件中说:

$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
}