简体   繁体   English

使用PowerShell转置CSV文件

[英]Transposing a CSV file using PowerShell

I have a CSV file that has a static number of columns (with headers) and a dynamic number of rows and I need convert it to another CSV which has a static number of rows and a dynamic number of columns (with or without headers). 我有一个CSV文件,它具有固定的列数(带标题)和动态的行数,我需要将其转换为另一个CSV,该CSV文件具有静态的行数和动态的列数(带或不带标题)。

Here is an example of what the before and after would look like in a spreadsheet. 这是一个电子表格前后的示例。 Please keep in mind that the top section would represent my input data and the bottom section is the desired state. 请记住,顶部将代表我的输入数据,底部是所需的状态。

CSV电子表格数据

Of course this is a small subset as I could have a user that has 50 groups and a user which may only have 1 group associated with it. 当然,这是一个很小的子集,因为我可以有一个拥有50个组的用户和一个只有1个与之相关联的用户。 This leaves me with not knowing the number of columns in advance so it has to be dynamic. 这使我不必事先知道列数,因此它必须是动态的。

I have tried using what I found on this post , but I am running into an issue trying to modify the code to fit my needs. 我已经尝试使用在这篇博文中找到的内容,但是在尝试修改代码以适应我的需求时遇到了问题。 The closest I have been able to do is create a row for each unique user ID but instead of having the corresponding group names in columns next to each user, they are set as the headers and no values for the users. 我能够做的最接近的操作是为每个唯一的用户ID创建一行,但是与其在每个用户旁边的列中没有对应的组名,而是将它们设置为标题,而不为用户设置任何值。

意外的当前结果

If you don't require headers or defined columns you could simply collect the values from the second column in a hashtable of arrays where you use the values from the first column as keys: 如果您不需要标题或已定义的列,则可以简单地从数组的哈希表中收集第二列的值,在该哈希表中,您可以使用第一列的值作为键:

$data = @{}
Import-Csv 'C:\path\to\input.csv' | ForEach-Object {
    $data[$_.UserID] += @($_.GroupName)
}

Then you can export the data to a text file like this: 然后,您可以将数据导出到文本文件,如下所示:

$data.Keys | ForEach-Object {
    $_ + ',' + ($data[$_] -join ',')
} | Set-Content 'C:\path\to\output.txt'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM