Forum Discussion

tcboeira's avatar
tcboeira
Brass Contributor
Feb 22, 2023

How to split rows into column by specific delimiter

Hello.
Good afternoon! Well, being direct:
 
The question of the output of the ";" to "," I solved it...
I have a routine that generates a CSV file, and it looks like this:

A B C D E F G
1,2,3,4,5a 5b 5c 5d,6,7

I would like it to look like this:
A B C D E F G
1,2,3,4,5a,6,7
1,2,3,4,5b,6,7
1,2,3,4,5c,6,7
1,2,3,4,5d,6,7
 
But the fundamental issue is that I need to preserve the contents of the other columns, replicating them to the rows...
 
As in the situation... While column E is 5a, 5b, 5c... Columns A, B, C and D must repeat their contents...
 
To achieve this scenario, I have opened it in Excel and done the "data transformation", asking it to divide the column by the space delimiter.
 
This operation, due to manual intervention, ends up taking longer than it should...
 
Via Powershell, how could I do this?
 
  • AndySvints's avatar
    AndySvints
    Steel Contributor

    Hello tcboeira,

    I am sure there are more concise and elegant ways to do it, but here is one of the options that also works:

     

     

    $Data=Import-Csv 'C:\input.csv'
    $ColumnName="E"
    $Result=New-Object System.Collections.Generic.List[PsObject]
    foreach($l in $data){
        $Items=$l.$ColumnName -split ' '
        $l.psobject.Properties.Remove($ColumnName)
        foreach($i in $Items){
            $ht=[ordered]@{}
            $l.psobject.properties | Foreach { $ht[$_.Name] = $_.Value }
            $ht=$ht+@{$ColumnName=$i}
            $Result.Add($(New-Object -TypeName psobject -Property $ht))
            $l.psobject.Properties.Remove($ColumnName)
        }
    }
    $Result

     

     

     

    Hope that helps.

    • tcboeira's avatar
      tcboeira
      Brass Contributor

      Hello,

      First of all, thanks for the reply and sorry for the delay in getting back to you...

       

      I think I failed to exemplify correctly...

      I extract some data, via CSV file, which returns me like this:

       

      COL1COL2COL3COL4
      11121314
      222223 24 25 2627
      33323334

       

      And I wish it could look like this:

      COL1COL2COL3COL4
      11121314
      22222327
      22222427
      22222527
      22222627
      33323334

       

      I even tried something using the example...

      Is that right? Is it for this purpose?

       

      AndySvints 

      • AndySvints's avatar
        AndySvints
        Steel Contributor

        Hello tcboeira,

        Yes, the code provided is exactly for the use case that you are describing.

        Here is the execution of it on your data set:

         

        One caveat is that the order of the columns will be messed up.  Column in question will be all the way in the end.

        Hope that helps. 

Resources