问题描述
我有以下 CSV 文件,我想将它们合并为一个 CSV
I have the following CSV files, I want to merge these into a single CSV
01.csv
apples,48,12,7
pear,17,16,2
orange,22,6,1
02.csv
apples,51,8,6
grape,87,42,12
pear,22,3,7
03.csv
apples,11,12,13
grape,81,5,8
pear,11,5,6
04.csv
apples,14,12,8
orange,5,7,9
所需的输出:
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
谁能提供有关如何实现这一目标的指导?最好使用 Powershell,但如果更容易,也可以使用 Perl 等替代品.
Can anyone provide guidance on how to achieve this? Preferably using Powershell but open to alternatives like Perl if that's easier.
谢谢 Pantik,您的代码输出接近我想要的:
Thanks Pantik, your code's output is close to what I want:
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
不幸的是,当条目不存在于 CSV 文件中时,我需要占位符"逗号,例如橙色,22,6,1,,,,,,5,7,9 而不是橙色,22,6,1,5,7,9
Unfortunately I need "placeholder" commas in place for when the entry is NOT present in a CSV file, e.g. orange,22,6,1,,,,,,5,7,9 rather than orange,22,6,1,5,7,9
更新:我希望按照文件名的顺序解析这些文件,例如:
UPDATE: I would like these parsed in order of the filenames, e.g.:
$myFiles = @(gci *.csv) | sort Name
foreach ($file in $myFiles){
问候
推荐答案
这是我的 Perl 版本:
Here is my Perl version:
use strict;
use warnings;
my $filenum = 0;
my ( %fruits, %data );
foreach my $file ( sort glob("*.csv") ) {
$filenum++;
open my $fh, "<", $file or die $!;
while ( my $line = <$fh> ) {
chomp $line;
my ( $fruit, @values ) = split /,/, $line;
$fruits{$fruit} = 1;
$data{$filenum}{$fruit} = \@values;
}
close $fh;
}
foreach my $fruit ( sort keys %fruits ) {
print $fruit, ",", join( ",", map { $data{$_}{$fruit} ? @{ $data{$_}{$fruit} } : ",," } 1 .. $filenum ), "\n";
}
这给了我:
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,,,
那么你对葡萄有一个错别字还是我误会了什么?
这篇关于Powershell/Perl:将多个 CSV 文件合并为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!