Search code examples
arraysstringpowershell

Powershell split every string in an array


So, I have no seen anything remotely helpful on google or SO about this.

I have an array of strings and I want to run -split on each string in the array and end up with an array containing arrays of strings.

However when I do this:

$Strings | % { $_ -split ($Sep) }

PS flattens the result and I end up with an array of strings containing the concatenated result of every -split.

E.g. For this

$Strings = @("a b c", "d e f")
$Sep = " "
$Strings | % { $_ -split ($Sep) } 

I get @("a", "b", "c", "d", "e", "f") but I want @( @("a", "b", "c"), @("d", "e", "f") ). What exactly am I not doing right?


Solution

  • You can either use the , comma operator:

    In expression mode, as a unary operator, the comma creates an array with just one member.

    $Strings = @('a b c', 'd e f')
    $Sep = ' '
    $result = $Strings | ForEach-Object { , ($_ -split $Sep) }
    $result[0]
    # a
    # b
    # c
    $result[1]
    # d
    # e
    # f
    

    Or Write-Output -NoEnumerate:

    The NoEnumerate parameter suppresses the default behavior, and prevents Write-Output from enumerating output.

    $Strings = @('a b c', 'd e f')
    $Sep = ' '
    $result = $Strings | ForEach-Object { Write-Output ($_ -split $Sep) -NoEnumerate }
    $result[0]
    # a
    # b
    # c
    $result[1]
    # d
    # e
    # f