Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.9k views
in Technique[技术] by (71.8m points)

Get Unique Column and Count from CSV file in Powershell

I have a CSV File called Products.csv

Product_ID,Category
1,A
2,A
3,A
4,B

I want a powershell script that will show me the Unique Categories along with the Count and export to CSV.

i.e.

A,3
B,1

I have used the following code to extract the Unique Categories, but cannot get the Count:

Import-Csv Products.csv -DeLimiter ","|
Select 'Category' -Unique |
Export-Csv Summary.csv -DeLimiter "," -NoTypeInformation

Can anyone help me out? Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Group-Object to get the count.

Import-Csv Products.csv -DeLimiter "," |
    Group-Object Category | Foreach-Object {
        "{0},{1}" -f $_.Name,$_.Count 
    }

If you want a CSV output of the count, you need headers for your data. Group-Object outputs property Name which is the grouped property value and Count which is the number of items in that group.

Import-Csv Products.csv -DeLimiter "," |
    Group-Object Category | Select-Object Name,Count |
        Export-Csv Summary.csv -Delimiter ',' -NoType

You can take the above code a step further and use Select-Object's calculated properties. Then you can create custom named columns and/or values with expressions.

Import-Csv Products.csv -DeLimiter "," |
    Group-Object Category |
        Select-Object @{n='Product_ID';e={$_.Name}},Count |
            Export-Csv Summary.csv -Delimiter ',' -NoType

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...