如何使用 PowerShell 计算文本文件中的对象 [英] How to count objects in text file using PowerShell
问题描述
我想知道如何使用 PowerShell 计算文本文件中的特定对象.
I'm wondering how I can count a particular objects in the text file using PowerShell.
例如,这是我拥有的文件:
For example, this is the file I have:
Color: Black
Length: Long
Size: 30
Color: Blue
Length: Long
Size: 20
Color: Black
Length: Short
Size: 10
我如何着色"?那是黑色"?
How do I "Color" that is "Black" ?
根据文件输出应该是2.
The output should be 2 according to the file.
推荐答案
您可以将文本作为单个多行字符串读取,然后在空行上将其分解为块.然后做一个简单的正则表达式来捕捉你想要的字符串并获取匹配块数的 Count 属性.
You can read the text as single multiline string and break it down into blocks on the empty line. Then do a simple regex to catch the string you want and get the Count property of the number of blocks that matched.
$colorToCount = 'Black'
((Get-Content -Path 'D:\Test\colors.txt' -Raw) -split '(\r?\n){2,}' |
Where-Object { $_ -match "(?m)^Color:\s*$colorToCount" }).Count
将使用您的示例文件返回 2
.
will return 2
using your example file.
如果您打算首先从该文本创建一个对象数组,您可以这样做:
If what you intend is to first create an array of objects from this text, you can do this:
# create an array of objects from the file
$data = (Get-Content -Path 'D:\Test\colors.txt' -Raw) -split '(\r?\n){2,}' |
Where-Object { $_ -match '\S' } | ForEach-Object {
[PsCustomObject]($_ -replace ':', '=' | ConvertFrom-StringData)
}
# now get the count of objects with the wanted color
$colorToCount = 'Black'
($data | Where-Object { $_.Color -eq $colorToCount }).Count
这篇关于如何使用 PowerShell 计算文本文件中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!