Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large string into array, but with a twist! (PowerShell)

Tags:

powershell

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.

like image 831
Josh B Avatar asked Oct 22 '25 05:10

Josh B


2 Answers

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'
  • For an explanation of the regex and the option to experiment with it, see this regex101.com page; in short, it uses a positive lookbehind assertion to match two consecutive (non-empty) lines, and splits by the subsequent newline.
like image 187
mklement0 Avatar answered Oct 23 '25 21:10

mklement0


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.

like image 21
Abraham Zinala Avatar answered Oct 23 '25 20:10

Abraham Zinala