2017-04-01 220 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

相關問題