0

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
  • 1
    If you are just trying to count the occurrences of a string in a CSV file import it as text not as a CSV and match the string that way. Or better, use Select-String on the file and specify the -allmatches parameter. Commented Apr 9, 2015 at 3:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try cycling through properties like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.