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

Powershell基于特定列对数据进行排序和转置,powershell,Powershell,我对powershell是新手。我有一个列格式的数据,需要通过数字排序将其转换为行。 输入数据: 期望输出: Fruit JanAmount FebAmount 1apple 10 20 2banana 50 95 3blueberry 20 50 4mango 30 80 有人能帮我吗?如果文件中的分隔符是空格,请尝试以下操作: import-csv "C:\Temp\yourfile.txt" -Delimiter ' ' | group fruit | sel

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

期望输出:

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

有人能帮我吗?

如果文件中的分隔符是空格,请尝试以下操作:

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

只要水果名称中没有空格,就可以将文件读取为CSV,并以空格作为分隔符。然后使用组对象合并它们,并添加成员以动态添加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  

在原始数据中,水果和数值之间没有空格?行之间还有额外的空格?这看起来像是家庭作业,如果你展示你的代码,甚至尝试使用它都可以。代码:get content$InSort | sort Fruit here$InSort是我的输入文件,我按第1列排序,即Fruit我们可以选择tab或修改它,因为Demiliter请编辑问题以包含新信息,所以其他人不需要通读所有的评论。水果月金额是文件中的标题吗?你不想把时间限制在一月和二月吗?谢谢你。它在命令行中运行良好。但当我将其导出到文本平铺时,它是这样的。希望我们能在这个网站上附加这个文件{Fruit=1apple;janmount=10;FebAmount=20}{Fruit=2banana;janmount=50;FebAmount=95}{Fruit=3blueberry;janmount=20;FebAmount=50}{Fruit=4mango;janmount=30;FebAmount=80}对不起,我没看到这个。我的实际文件很大。大约600MB。因此,我使用.txt格式。这只需将扩展名更改为.txt即可。多谢一顿::所以将其更改为newfile.txt。文件扩展名只是表面的。此外,此解决方案速度较慢,并且需要一些内存来存储该大小的文件。请在以后的问题中包括这些细节……我被另一个问题困住了,我把第1栏列为年,第3栏列为月,有没有一种方法可以连接列?2015年1月,2015年1月,2015年2月它应该创建一个新的栏目,如2015年1月,2015年1月,2015年2月,2015年2月,2015年2月
Fruit      JanAmount FebAmount
-----      --------- ---------
1apple     10        20       
2banana    50        95       
3blueberry 20        50       
4mango     30        80