Powershell根据特定列对数据进行排序和转置

时间:2017-04-01 06:22:42

标签: powershell

我是PowerShell的新手。我有一个柱状格式的数据,需要通过数字排序将其转换为行 输入数据:

Fruit month amount
1apple jan 10 
3blueberry jan 20
4mango jan 30
2banana jan 50
1apple feb 20 
3blueberry feb 50
4mango feb 80
2banana feb 95

期望的输出:

Fruit JanAmount FebAmount
1apple 10 20
2banana 50 95
3blueberry 20 50
4mango 30 80

任何人都可以帮我这个吗?

2 个答案:

答案 0 :(得分:2)

只要水果名称中没有空格,您就可以将文件读取为CSV,并以空格作为分隔符。然后使用Group-ObjectAdd-Member合并它们以动态添加x个月。例如:

Import-Csv -Path $InSort -Delimiter " " |
#Group all records per fruit
Group-Object Fruit |
#Sort by fruitname
Sort-Object Name |
#Process each group (fruit) to merge the rows
ForEach-Object {
    #Create object (row) per fruit
    $obj = New-Object -TypeName psobject -Property @{
        Fruit = $_.Name
    }

    #For each record (month), add amount column
    $_.Group | ForEach-Object {
        #Turn month-value into TitleCase (first letter uppercase)
        $month = (Get-Culture).TextInfo.ToTitleCase($_.Month)
        #Add amount-column per record (month)
        Add-Member -InputObject $obj -MemberType NoteProperty -Name "$($Month)Amount" -Value $_.Amount
    }

    #Output new objects
    $obj
} | Export-CSV -Path newfile.csv -NoTypeInformation -Delimiter " "

输出:

Fruit      JanAmount FebAmount
-----      --------- ---------
1apple     10        20       
2banana    50        95       
3blueberry 20        50       
4mango     30        80  

答案 1 :(得分:0)

如果您将文件分隔到空间,请尝试以下操作:

import-csv "C:\Temp\yourfile.txt" -Delimiter  ' ' | 
    group fruit |
        select Name, @{N="JanAmount";E={($_.Group | where month -eq 'jan').amount}} , @{N="FebAmount";E={($_.Group | where month -eq 'feb').amount}}