Powershell counting same values from csv

巧了我就是萌 提交于 2020-01-22 02:26:08

问题


Using PowerShell, I can import the CSV file and count how many objects are equal to "a". For example,

@(Import-csv location | where-Object{$_.id -eq "a"}).Count

Is there a way to go through every column and row looking for the same String "a" and adding onto count? Or do I have to do the same command over and over for every column, just with a different keyword?


回答1:


Try cycling through properties like this:

(Import-Csv location | %{$record = $_; $record | Get-Member -MemberType Properties | 
    ?{$record.$($_.Name) -eq 'a';}}).Count



回答2:


So I made a dummy file that contains 5 columns of people names. Now to show you how the process will work I will show you how often the text "Ann" appears in any field.

$file = "C:\temp\MOCK_DATA (3).csv"
gc $file | %{$_ -split ","} | Group-Object | Where-Object{$_.Name -like "Ann*"}

Don't focus on the code but the output below.

Count Name  Group                          
----- ----  -----                          
    5 Ann   {Ann, Ann, Ann, Ann...}        
    9 Anne  {Anne, Anne, Anne, Anne...}    
   12 Annie {Annie, Annie, Annie, Annie...}
   19 Anna  {Anna, Anna, Anna, Anna...} 

"Ann" appears 5 times on it's own. However it is a part of other names as well. Lets use a simple regex to find all the values that are only "Ann".

(select-string -Path 'C:\temp\MOCK_DATA (3).csv' -Pattern "\bAnn\b" -AllMatches | Select-Object -ExpandProperty Matches).Count

That will return 5 since \b is for a word boundary. In essence it is only looking at what is between commas or beginning or end of each line. This omits results like "Anna" and "Annie" that you might have. Select-Object -ExpandProperty Matches is important to have if you have more than one match on a single line.

Small Caveat

It should not matter but in trying to keep the code simple it is possible that your header could match with the value you are looking for. Not likely which is why I don't account for it. If that is a possibility then we could use Get-Content instead with a Select -Skip 1.



来源:https://stackoverflow.com/questions/29529154/powershell-counting-same-values-from-csv

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