Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

How do I merge every csv file in the directory?

by luxlunae (Novice)
on Jun 27, 2012 at 17:32 UTC ( [id://978726]=perlquestion: print w/replies, xml ) Need Help??

luxlunae has asked for the wisdom of the Perl Monks concerning the following question:

I want this to look at every csv file in the directory and append them all to each other in an output.txt.
open(MYOUTFILE, ">output.txt"); #open for write, overwrite my $filecount = 0; my @filenames; ###code that assigns all the csv file names in the present folder #to an array and counts them foreach $inputfilename (@filenames) { open INPUT, "<$inputfilename"; @lines = <INPUT>; close INPUT; foreach $row (@lines) { print MYOUTFILE ("$row\n"); } close INPUT; } close MYOUTFILE; my $ovr = <STDIN>; exit;
As you can see my weakness is actually getting all of the csv file names into an array. I think this is going to be solved with a map command but I wasn't able to figure it out myself.

Replies are listed 'Best First'.
Re: How do I merge every csv file in the directory?
by choroba (Cardinal) on Jun 27, 2012 at 17:36 UTC

      For windows, replace cat with type: type *.csv > out.txt

      Thanks!
Re: How do I merge every csv file in the directory?
by Jim (Curate) on Jun 27, 2012 at 18:51 UTC
    As you can see my weakness is actually getting all of the csv file names into an array. I think this is going to be solved with a map command but I wasn't able to figure it out myself.

    Consider using @ARGV instead of hardwiring the input file names inside the script. And also consider using STDOUT instead of hardwiring the output file name inside the script.

    I like File::Glob::bsd_glob().

    #!perl use strict; use warnings; use English qw( -no_match_vars ); use File::Glob qw( bsd_glob ); @ARGV or die "Usage: perl $PROGRAM_NAME <CSV file> ...\n"; @ARGV = map { bsd_glob($ARG) } @ARGV; while (my $row = <ARGV>) { # Presumably, something useful happens to $row here; # otherwise this script is just cat(1) in Perl print $row; } exit 0;

    Jim

Re: How do I merge every csv file in the directory?
by Anonymous Monk on Jun 27, 2012 at 17:36 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://978726]
Approved by muba
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-03-28 23:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found