PowerShell更改字符串的内容

时间:2014-08-19 13:55:26

标签: string powershell

我希望能够更改此字符串:

$Result
Header 1,Text 1,Text 11,,,,,
Header 2,Text 2,Text 22,,,,,
Header 3,Text 3,Text 33,,,,,
Header 4,,Text 44,,,,,

在此字符串中:

$Result
Header 1,Header 2,Header 3,Header 4
Text 1,Text 2,Text 3,,
Text 11,Text 22,Text 33,Text 44

当它只涉及一个标题和一个文本项时,我设法做到了这一点。但我无法弄清楚如何动态执行此操作,以防我不知道将跟随多少文本项。然后,ConvertFrom-Csv将导入此字符串以供日后使用。

我当前的代码适用于一个标题和一个文本项:

$Result | ForEach-Object {$Header += "$($_.Split(',')[0]),"; $Content += "$($_.Split(',')[1]),"}
$Result = "$Header`n$Content"

解决方案,感谢以下人员:

Function ConvertTo-ReverseCSV {
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param (
        [parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [String] $String
    )

    PROCESS {
        $StringMax = 0
        $h = @()

        $String.split("`n") | % {
            $a = $_.split(",")
            $h += ,$a
            if($a.length -gt $StringMax) { $StringMax = $a.length }
        }

        for($j = 0; $j -lt $StringMax; $j++) {
            for($i = 0; $i -lt $h.length; $i++) {
                $Result += "$($h[$i].split("`n")[$j]),"
            }
            $Result +="`n"
        }
        Write-Output $Result
    }
}

2 个答案:

答案 0 :(得分:2)

我认为以下内容将进行您需要的转换:

$r = @'
Header 1,Text 1,Text 11,,,,,
Header 2,Text 2,Text 22,,,,,
Header 3,Text 3,Text 33,,,,,
'@

$rmax = 0
$h = @()

$r.split("`n") | % {
    $a = $_.split(",")
    $h += ,$a
    if($a.length -gt $rmax) { $rmax = $a.length }
}

for($j = 0; $j -lt $rmax; $j++) {
    for($i = 0; $i -lt $h.length; $i++) {
        write-host -nonewline "$($h[$i].split("`n")[$j]),"
    }
    write-host ""
}

如果适合您,您可以将其整理成一个功能。

答案 1 :(得分:0)

看起来像矩阵转置问题。你可以尝试这样的事情:

C:\PS> $data = @()
C:\PS> @'
>>> Header 1,Text 1,Text 11,Text 111
>>> Header 2,Text 2,Text 22,Text 222
>>> Header 3,Text 3,Text 33,Text 333
>>> '@ -split "`n" | Foreach {$data += ,($_ -split ',')}
C:\PS> $trans = new-object object[] -arg $data[0].length
C:\PS> for ($i=0;$i -lt $trans.length;$i++) { $trans[$i] = new-object string[] $data.length }
C:\PS> for ($i=0;$i -lt $data.Length; $i++) {
>>>     for ($j=0;$j -lt $data[0].Length; $j++) {
>>>         $trans[$j][$i] = $data[$i][$j]
>>>     }
>>> }
C:\PS> $trans
Header 1
Header 2
Header 3
Text 1
Text 2
Text 3
Text 11
Text 22
Text 33
Text 111
Text 222
Text 333