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

2024-02-22

我是 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与流阅读器?


您可以使用ToCharArray and where找到匹配项。例如,要计算文件中“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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐