使用CSV文件

时间:2014-06-18 02:53:36

标签: powershell csv

假设我在data.csv中有这样的表:

time    channel x   y   z
0.001   point 1 1   2   3
0.001   point 2 4   5   6
0.001   point 3 7   8   9
0.001   point 4 10  11  12
0.001   point 5 13  14  15

0.002   point 1 2   3   4
0.002   point 2 5   6   7
0.002   point 3 8   9   10
0.002   point 4 11  12  13
0.002   point 5 14  15  16

0.004   point 1 3   4   5
0.004   point 2 6   7   8
0.004   point 3 9   10  11
0.004   point 4 12  13  14
0.004   point 5 15  16  17

如何让Powershell写出3个文件(Xdata.csv,Ydata.csv,Zdata.csv),Xdata.csv应如下所示:

time    point 1 point 2 point 3 point 4 point 5
0.001   1       4       7       10      13
0.002   2       5       8       11      14
0.004   3       6       9       12      15

到目前为止,我的代码看起来像这样:

# Path to current directory
$path = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)

# csv filename to be imported from
$filename = "data.csv"

$data = Import-Csv "$path\$filename"

# Array of unique values of times
$times = $data | % { $_.time } | Sort-Object | Get-Unique

# Array of unique values of channels
$channels = $data | % { $_.channel } | Sort-Object | Get-Unique

但是在这一点上,我正在努力设置如上所述的输出表。

2 个答案:

答案 0 :(得分:2)

我会使用Group-Object +一些逻辑来使用来自每个'时间的数据生成对象。快照

$collections = @{
    x = @()
    y = @()
    z = @()
}


$data | Group time | ForEach-Object {
    $x = New-Object PSObject -Property @{
        time = $_.Name
    }

    $y = New-Object PSObject -Property @{
        time = $_.Name
    }        

    $z = New-Object PSObject -Property @{
        time = $_.Name
    }        

    foreach ($item in $_.Group) {
        if ($item.channel) {
            $x | Add-Member -MemberType NoteProperty -Name $item.channel -Value $item.x
            $y | Add-Member -MemberType NoteProperty -Name $item.channel -Value $item.y
            $z | Add-Member -MemberType NoteProperty -Name $item.channel -Value $item.z
        }
    }

    $collections.x += $x
    $collections.y += $y
    $collections.z += $z

}

foreach ($coordinate in 'x','y','z') {
    $collections.$coordinate | Export-Csv -NoTypeInformation "${coordinate}data.csv"
}

这是假设数据'包含类似于我可以生成的对象:

New-Object PSObject -Property @{
    time = 0.001
    channel = 'point 1'
    x = 1
    y = 2
    z = 3
}

答案 1 :(得分:0)

更多的管道方法(未经测试)

$axes = @{
x = [ordered]@{}
y = [ordered]@{}
z = [ordered]@{}
}

import-csv data.csv |
 foreach-object {
  if ( $axes.x.containskey($_.time) )
   {
     foreach ($axis in 'x','y','z')
      { $axes.$axis[$_.time].add($_.channel,$_.$axis) } 
   }

  else { 
        foreach ($axis in 'x','y','z')
        { $axes.$axis[$_.time] = [ordered]@{ time = $_.time;$_.channel = $_.$axis } }
       }
 }

 foreach ($axis in 'x','y','z')
  {
   $(foreach ($time in $axes.$axis.values)
   { [PSCustomObject]$time })| 
     export-csv ${$axis}data.csv -NoTypeInformation 
  }