我有以下CSV文件,我想将它们合并为一个CSV
01.csv
apples,48,12,7
pear,17,16,2
orange,22,6,1
Run Code Online (Sandbox Code Playgroud)
02.csv
apples,51,8,6
grape,87,42,12
pear,22,3,7
Run Code Online (Sandbox Code Playgroud)
03.csv
apples,11,12,13
grape,81,5,8
pear,11,5,6
Run Code Online (Sandbox Code Playgroud)
04.csv
apples,14,12,8
orange,5,7,9
Run Code Online (Sandbox Code Playgroud)
期望的输出:
apples,48,12,7,51,8,6,11,12,13,14,12,8
grape,,,87,42,12,81,5,8,,,
pear,17,16,2,22,3,7,11,5,6,,,
orange,22,6,1,,,,,,5,7,9
Run Code Online (Sandbox Code Playgroud)
谁能提供如何实现这一目标的指导?最好使用Powershell,但如果更容易,可以使用Perl等替代品.
感谢Pantik,您的代码输出接近我想要的:
apples,48,12,7,51,8,6,11,12,13,14,12,8
grape,87,42,12,81,5,8
orange,22,6,1,5,7,9
pear,17,16,2,22,3,7,11,5,6
Run Code Online (Sandbox Code Playgroud)
不幸的是,当CSV条目中没有条目时,我需要"占位符"逗号,例如橙色,22,6,1 ,,,,,, 5,7,9而不是橙色,22,6,1, 5,7,9
更新:我想按文件名的顺序解析这些,例如:
$myFiles = @(gci *.csv) | sort Name
foreach ($file in $myFiles){
Run Code Online (Sandbox Code Playgroud)
关于泰德
你必须解析文件,我没有看到更简单的方法
powershell中的解决方案:
更新:好的,调整了一下 - 希望可以理解
$items = @{}
$colCount = 0 # total amount of columns
# loop through all files
foreach ($file in (gci *.csv | sort Name))
{
$content = Get-Content $file
$itemsToAdd = 0; # columns added by this file
foreach ($line in $content)
{
if ($line -match "^(?<group>\w+),(?<value>.*)")
{
$group = $matches["group"]
if (-not $items.ContainsKey($group))
{ # in case the row doesn't exists add and fill with empty columns
$items.Add($group, @())
for($i = 0; $i -lt $colCount; $i++) { $items[$group] += "" }
}
# add new values to correct row
$matches["value"].Split(",") | foreach { $items[$group] += $_ }
$itemsToAdd = ($matches["value"].Split(",") | measure).Count # saves col count
}
}
# in case that file didn't contain some row, add empty cols for those rows
$colCount += $itemsToAdd
$toAddEmpty = @()
$items.Keys | ? { (($items[$_] | measure).Count -lt $colCount) } | foreach { $toAddEmpty += $_ }
foreach ($key in $toAddEmpty)
{
for($i = 0; $i -lt $itemsToAdd; $i++) { $items[$key] += "" }
}
}
# output
Remove-Item "output.csv" -ea 0
foreach ($key in $items.Keys)
{
"$key,{0}" -f [string]::Join(",", $items[$key]) | Add-Content "output.csv"
}
Run Code Online (Sandbox Code Playgroud)
输出:
apples,48,12,7,51,8,6,11,12,13,14,12,8
grape,,,,87,42,12,81,5,8,,,
orange,22,6,1,,,,,,,5,7,9
pear,17,16,2,22,3,7,11,5,6,,,
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2640 次 |
| 最近记录: |