powershell转置并只保留一组标题

时间:2017-07-26 21:13:20

标签: excel powershell

我的数据集如下所示

headers            data
ip                 192.168.1.1  
netmask            255.255.255.0
description        class C
ip                 172.20.1.1  
netmask            255.255.0.0
description        class B
ip                 10.0.0.1  
netmask            255.255.255.0
description        class A

如何将其转换为我预期的输出:

ip           netmask          description
192.168.1.1  255.255.255.0    class C
172.20.1.1   255.255.0.0      class B
10.0.0.1     255.0.0.0        class A

目前我正在从CSV导入此数据,如下所示:

$data = import-csv .\data.txt -headers headers,data

如果有一种简单的方法可以在excel中执行此操作,那也很棒。

任何帮助都会很棒。谢谢。

2 个答案:

答案 0 :(得分:1)

#Import data

\main
    \java
    \resources
    \scala
        -funcJM(class)
    \scala-2.11

#Remove第一行

$data = Import-Csv .\data.txt -headers headers,data
$data | FT -AutoSize

#Convert the table

get-content $data | select -Skip 1 | set-content "$data-temp"
move "$data-temp" $data -Force

newData.csv应如您所愿,如果没有,请再次告诉我。

答案 1 :(得分:1)

之前的回答没有使用问题中指定的数据,这个问题就是这样。它也有充分的评论来解释它的作用。代码下面是它的工作原理:

$newrow = @{} # newrow contains the values on an output row at any given time
$newtable = [System.Collections.ArrayList]@() # newtable contains the final output

# Loop through each row in the input data, assign oldrow to the current row
foreach($oldrow in $data) {
    # If the output row already has an ip, netmask or description, then start a new row (hashtable) and add the current row (hashtable) to output
    if ($newrow[$oldrow.headers] -ne $null) {
        Write-Host "$($oldrow.headers) Already found. Adding new row to output" -ForegroundColor Green 
        # Add the current row to the target object
        [void]$newtable.Add($(New-Object PSObject -Property $newrow))
        # Create a new empty row (hashtable)
        $newrow = @{}
    }
    # For each iteration, keep adding data
    Write-Host "Adding new entry for $($oldrow.headers)" 
    $newrow[$oldrow.headers] = $oldrow.data
}

# The final row is not added to the table within the loop, so it must be added here
Write-Host "Loop finished, adding final row to output" -ForegroundColor Green
[void]$newtable.Add($(New-Object PSObject -Property $newrow))

$newtable | select ip,netmask,description

假设

遇到具有相同标头值的记录时,需要新行。在此之前,应将记录添加到同一行,标题值提供新的列名称。

过程

  1. 设置一个名为$ newrow的哈希表。
  2. 设置名为$ newtable的ArrayList。 ArrayLists比标准数组更灵活,因为它们具有Add()方法。
  3. 使用foreach循环迭代数据
  4. 以if语句开头,该语句处理查找包含我们已分配的列的记录。此时使用Write-Host触发消息,添加旧行并设置新行。在foreach循环的第一次迭代中,由于散列表为空,因此总是求值为false。
    1. if条件之外的块中,继续向哈希表添加值。
    2. 最后,添加最后一行,然后使用select-object以正确的顺序打印输出。