causita
causita

Reputation: 1708

Create files from master csv file based on field

I have a CSV dump with about 10 k rows. I'm trying to split this in multiple files based on a store field using Powershell.

Master File Content

Date,   Store,  Product
11/16    NYC    100
11/16    NYC    101
11/16    BOS    100
11/16    BOS    101

Based on this data, I need to create a file for NYC and another for BOS with their corresponding contents.

I want something that is fast. I thought about looping each line and check the line before and compare but I thought may it was too slow.

Then I thought of using Group-Object cmdlet

import-csv  C:\masteFile.csv | Group-Object{$_.store}
The output is
Count Name  Group 
2      NYC   {@{DATE=11/06; STORE=NYC; PRODUCT=100},{@{DATE=11/06; STORE=NYC; PRODUCT=101}}
3      BOS   {@{DATE=11/06; STORE=BOS; PRODUCT=100},{@{DATE=11/06; STORE=BOS; PRODUCT=101}}... AND SO ON

I'm trying to get the contents from each object and create a new file.

Upvotes: 0

Views: 244

Answers (1)

kim
kim

Reputation: 3421

Try running

Import-Csv  C:\masteFile.csv | Group-Object Store | ForEach-Object { $_.Group | Export-Csv "$($_.Name).csv" }

It reads the input file, groups the contents of the input and then for each group in the result creates a new csv file, containing the groups contents, having the name of the group.

Upvotes: 2

Related Questions