简体   繁体   English

如何使用正则表达式转置 PowerShell 的矩阵?

[英]How to transpose a matrix with PowerShell using regex?

To accomplish with powershell :完成powershell

Original原版的 Transposed移调
0 1 2 3 0 1 2 3
ab c d电话 c
# $ @ % #$@%

 0 a # 0个#
1 b $ 1 英镑
2 c @ 2 c @
3 d % 3天%

how can a magic number be used (some regex in practice) where each original row has a variable number of columns so that only when the keyword occurs does that initiate a transpose?如何在每个原始行都有可变数量的列的情况下使用幻数(实践中的一些正则表达式),以便只有当关键字出现时才会启动转置?

Assuming that the original matrix is n x 2 so something like:假设原始矩阵是n x 2所以类似于:

a 1
b 2
c 3
d 4
a 5
d 6
a 7
b 8
c 9

The resulting matrix may very well be sparse, but each occurrence of a would signify a new column of output.生成的矩阵很可能是稀疏的,但每次出现a都表示一个新列 output。

To transpose Rows to column conversion of file with powershell:要使用 powershell将文件的行转为列转换
(Note that there is nothing in the referral that shows how magic numbers should be used to accomplish this) (请注意,推荐中没有任何内容显示应如何使用幻数来完成此操作)

$Orginal = @'
0 1 2 3
a b c d
# $ @ %
'@

$Transposed = [Collections.ObjectModel.Collection[Object]]::new()
$Lines = $Orginal -Split '\r?\n'
for ($y = 0; $y -lt $Lines.Count; $y++) {
    $Items = $lines[$y] -Split '\s+'
    for ($x = 0; $x -lt $Items.Count; $x++) {
        if ($x -ge $Transposed.Count) { $Transposed.Add((,@() * $Lines.Count)) }
        $Transposed[$x][$y] = $Items[$x]
    }
}

$Transposed |Foreach-Object { "$_" }

0 a #
1 b $
2 c @
3 d %

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM