T
T
the Alekhnovich2021-08-17 17:56:50
PowerShell
the Alekhnovich, 2021-08-17 17:56:50

How to split a CSV file into two by the number of items per line?

Hey!
There is a .CSV file containing names, usernames and groups. I need to divide this file into two others by the number of groups: in one file - users with one group, in the second - with several groups.

The .CSV file looks like this:

Name UserName Group
Bob Bob.B Legion
Jake Jake NCR
Kayne Kayne.S Neuntral,Brotherhood
Stacy Stacy.H Bombers
Alan Alen Trader,NCR
Sten Sten.P Neutral
Peter Peter.K Farmer,NCR

I think you should use a ForEach loop, but I don't know how to extract single and multiple values ​​from the third column, where the groups are indicated.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2021-08-17
@Uladz

Something like that

$data=Import-csv src
$data | where-object { $_.Group -match ',' } | export-csv dstg2
$data | where-object { $_.Group -notmatch ','  } | export-csv dstg1

Paths, separators, encoding - your own

V
Vasily Bannikov, 2021-08-17
@vabka

For example like this:

$file = "./data.csv"
$singleFactionFile = "./single.csv"
$manyFactionsFile = "./many.csv"

$content = $file | Get-Content
$lines = $content.Split("`n")
$header = $lines[0]
$data = $lines | Select-Object -Skip 1
Add-Content -Path $singleFactionFile -Path $manyFactionsFile -Value $header 

foreach ($line in $data) {
    $fields = $line.Split(' ')
    $factions = $fields[2].Split(',')
    if ($factions.Count -eq 1) {
        Add-Content -Path $singleFactionFile -Value $line
    }
    else {
        Add-Content -Path $manyFactionsFile -Value $line
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question