使用Perl合并多个csv文件

时间:2013-08-01 12:21:08

标签: perl csv merge

我是Perl的新手,很抱歉这个简单的问题。

我有一个生成7个csv文件的Perl脚本。所有这些文件都有8个常用列标题。

文件名将保持不变,每个文件只有8列,每列的每个值总是有数据。

每个文件的大小永远不会超过400k。

我想使用Perl将这些csv文件合并到一个文件中。输出将具有相同的列标题和来自所有7个文件的数据。

1 个答案:

答案 0 :(得分:3)

如果您使用的是某种Unix,则可以使用tail

$ tail -qn +2 fileA fileB ...

-q取消输出中的文件名; -n +2以第二行开始输出。

要获得标题:

$ (head -n 1 fileA; tail -qn +2 fileA fileB ...) > output-file

如果您需要使用Perl:

use strict; use warnings; use autodie;
my $files = $#ARGV; # get number of files - 1
while (my $file = shift @ARGV) {
  open my $fh, "<", $file;
  <$fh> unless $files == @ARGV; # discard header unless first file
  print while <$fh>; # output the rest
}

然后:$ perl the-script.pl fileA fileB ...

相关问题