How to count objects in text file using PowerShell

£可爱£侵袭症+ 提交于 2021-02-20 03:51:08

问题


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" ?

The output should be 2 according to the file.


回答1:


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

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



回答2:


I suppose your file is always same format :

#decomposition of your file into list of formated objects
$Objects=Get-Content "C:\temp\sample.txt" | where {$_ -ne ""} | %{

$Match=$_ -split "(?<Color>Color:.+)(?<Length>Length:.+)(?<Size>Size:.+)"

[pscustomobject]@{
Color=($Match[1] -split ": ")[1].trim()
Length=($Match[2] -split ": ")[1].trim()
Size=($Match[3] -split ": ")[1].trim()
}


} 

#Found object with color black
$Objects | where {$_.Color -eq 'Black'}

#Found number of object with color black
($Objects | where {$_.Color -eq 'Black'} | Measure-Object).Count

#you can use group too :)
$Objects | group Color

#you can use group too for found number of black ;)
($Objects | group Color | where Name -eq 'Black').Count


来源:https://stackoverflow.com/questions/65416910/how-to-count-objects-in-text-file-using-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!