powershell - Better alternative to pivot rows into columns -
trying stack these columns in powershell, , works! however, feels there should easier way this. please let me know if have alternatives accomplish same goal
$lines = @' 5 b d7 e c f '@ $lines = $lines.split("`n") $max = $lines | % {$_.trim().split(' ').count} | sort -desc | select -f 1 $count = 0 $obj = new-object psobject foreach ($line in $lines) { $obj | add-member -membertype noteproperty -name $count -value $line $count++ } ($x = 0; $x -lt $count; $x++) { ($y = 0; $y -lt $count; $y++) { $obj.$y.trim().split(' ')[$x] } } desired output this:
5 b c d7 f e here's more random example of input , desired output. script:
$alpha = 65..90 | % { [char]$_ } $lines = ($i = 0; $i -lt $alpha.count; $i ++) { $line = '' $cols = get-random -minimum 1 -maximum 6 ($j = 0; $j -lt $cols; $j++) { $line += $alpha[$i+$j] + ' ' } $line.trim() $i = $i + $cols - 1 } $lines = $lines.split("`n") $lines # rest of code same above. the first section shows array. second section shows want like. (reminder: script works, looking alternatives)
a b c d e f g h j k l m n o p q r s t u v w x y z b f h j k o p t x c g l q u y d m r v z e n s w
given $lines 1 of here-strings have above work fine. text coming file easy insert here.
$linesarray = $lines -split "`r`n" | foreach-object{,($_.trim() -split '\s')} $columns = ($linesarray | measure-object count -maximum).maximum $result = for($index =0; $index -lt $columns;$index++){ $linesarray | where-object {$index -lt $_.length} | foreach-object{$_[$index]} | where-object{![string]::isnullorempty($_)} } where $result contains "transposed" arrray. split $lines lines , each line split on spaces (trim()ed in case of trailing spaces found in example).
count maximum columns know how our loop structured. call nth element of each line in order. nulls ignored calling non exiting elements non issue.
tested powershell v4 can downgraded easy if need be. $columns thing need changed.
i made couple of changes address comments. if strict mode enabled flags accessing non-existent elements simple clause prevent accessing elements no exist. proper address nulls returned in case of post processing issues.
Comments
Post a Comment