如何使用 Powershell 中的 StreamReader 类来查找和计算文件中包含的字符数? [英] How to use the StreamReader class in Powershell to find and count number of characters contained in a file?
问题描述
我是 powershell 的新手,没有使用 .net 的经验.我有一个使用
的脚本(get-content | select-string -pattern -allmatches).matches |测量对象
查找并计算文件中的字符数.如果文件只包含少于 10k 行,我的脚本将正常工作.否则对于大文件,RAM 将达到 100%,然后 Powershell 将显示(无响应)
I'm new to powershell and have no experience with .net. I have a script that use
(get-content | select-string -pattern -allmatches).matches | measure-object
to find and count how many characters in a file. My script will work fine if the file only contain less than a 10k rows. Otherwise for big file, the RAM will shoot up to 100% and then the Powershell will display (Not Responding)
我做了一些研究,发现 system.io.streamreader 可以工作,我在 Stackoverflow 中阅读了几个问题,要查找和匹配文件中的字符或单词,您只需执行以下操作:
I did some research and I found out system.io.streamreader will work, I read a couple of questions in Stackoverflow and to find and match the character or word in a file you just need do this:
$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 |测量对象
与流阅读器?
but this is only returning the number of lines that contain the character, but not the number of characters in a file. So how do I use (select-string -inputobject -pattern -allmatches).matches | measure-object
with the streamreader?
推荐答案
您可以使用 ToCharArray
和 where
来查找匹配项.例如,要计算文件中e"的数量,您可以说:
You can use ToCharArray
and where
to find the matches. For example, to count the number of "e" in the file you can say:
$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
}
这篇关于如何使用 Powershell 中的 StreamReader 类来查找和计算文件中包含的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!