So, I have a single large string that looks something like:
Date, Status, Data
More Data about above line
Date, Status, Data
More Data about above line
Date, Status, Data
More Data about above line
Date, Status, Data
More Data about above line
Date, Status, Data
More Data about above line
And so forth. I've converted this into an array, but you might see the issue based on the information above.
The array now looks like:
$array[0]
Date, Status, Data
$array[1]
More Data about above line
I would like to take every two lines in the large string and make that a single entry into the array, so it looks like:
$array[0]
Date, Status, Data
More Data about the above line
Is there a simple way to do this?
This is the code I'm using to split it up from a large string to array:
$in = "your text"
$lines = $in.Split([Environment]::NewLine) | ? { $_ -ne "" }
The above examples explain pretty well what I'm seeing. I'm able to tear the large string apart and stuff it into an array, but the output is less than ideal, because I want every two lines in the large string grouped into a single array entry.
The regex-based -split operator enables a concise solution:Tip of the hat to Santiago Squarzon for help with the regex.
$in = @'
Date, Status, Data
More Data about above line1
Date, Status, Data
More Data about above line2
Date, Status, Data
More Data about above line3
Date, Status, Data
More Data about above line4
Date, Status, Data
More Data about above line5
'@
$array =
$in -split '(?m)(?<=\G^.+\n.+)\r?\n'
Just to not get rusty myself, here's an alternative approach to complement the other answers, using the less commonly used $foreach variable inside a foreach statement.
$array = @'
Date, Status, Data
More Data about above line1
Date, Status, Data
More Data about above line2
Date, Status, Data
More Data about above line3
Date, Status, Data
More Data about above line4
Date, Status, Data
More Data about above line5
'@ -split "\r?\n"
$new_array = foreach ($line in $array) {
$previous = $line
$null = $foreach.MoveNext()
@($previous, $foreach.Current) -join "`n"
}
By saving the current iteration $line to $previous before calling on .MoveNext(), as the method name may imply, we can join it with the next iteration by referencing $foreach.Current and passing both lines to our -join operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With