user2641999
user2641999

Reputation: 13

Merge multiple csv files using Perl

I am new to Perl so sorry for the simple question.

I have a Perl script that produces 7 csv files. All these files have 8 common column headings.

The file names will be constant, each file only has 8 columns and there will always be data in each value for each column.

The file size for each is never bigger than 400k.

I would like to combine these csv files into one file using Perl. The output will have the same column heading and data from all the 7 files.

Upvotes: 0

Views: 4271

Answers (1)

amon
amon

Reputation: 57656

If you are on some kind of Unix, you can use tail.

$ tail -qn +2 fileA fileB ...

The -q supresses filenames in the output; the -n +2 starts output with the 2nd line.

To get the header as well:

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

If you need to use 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
}

Then: $ perl the-script.pl fileA fileB ...

Upvotes: 6

Related Questions