2017-04-01 140 views
-1

我是Powerhell的新手。我有一个列表格式的数据,需要通过数字排序将其转换为行。
输入数据: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 

任何人都可以请帮助我?

+0

所以有在原始数据'Fruit'和数值之间没有空间?和行之间多余的空白? – 4c74356b41

+1

这看起来像家庭作业,如果你显示你的代码甚至是尝试它,那就没关系。 – LotPings

+0

代码:get-content $ InSort |排序水果 (这里$ insort是我的输入文件,我排序第1列,即水果) 我们可以采取选项卡或修改它,作为demiliter – PerlBatch

回答

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 
+0

谢谢弗罗德。 它在cmd行中正常工作。但是当我将它导出到文本拼贴时,它就是这样。希望我们可以选择在本网站上附加文件 @ {Fruit = 1apple; JanAmount = 10; FebAmount = 20} @ {Fruit = 2banana; JanAmount = 50; FebAmount = 95} @ {Fruit = 3blueberry; JanAmount = 20; FebAmount = 50} @ {Fruit = 4mango; JanAmount = 30; FebAmount = 80} – PerlBatch

+0

对不起,我错过了。我的实际文件是巨大的。大约600MB。所以,我使用.txt格式 – PerlBatch

+0

这个工作只是通过改变扩展名为.txt 感谢吨:) :) – PerlBatch

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}} 
+0

什么是重点,为什么不直接输入空格? – 4c74356b41

+0

可能也是修改我的代码 – Esperento57

相关问题