CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
[Edit .CSV file] Add column

 



srenin
New User

Nov 8, 2010, 10:13 PM

Post #1 of 4 (2212 views)
[Edit .CSV file] Add column Can't Post

I have several .CSV files with the same number of columns but different number of rows. I want to add a column where the rows are the filenames.

Example:
ex1.csv
ex2.csv
ex3.csv

In each .CSV, there is 5 columns, and the first row contains the headers. I want to add a 6th column where each row just contains "ex1" for ex1.csv, "ex2" for ex2.csv, and "ex3" for ex3.csv.

A sample line:
Col1,col2,col3,col4,col5

Becomes:
Col1,col2,col3,col4,col5,ex1


Zhris
Enthusiast

Nov 9, 2010, 1:38 AM

Post #2 of 4 (2207 views)
Re: [srenin] [Edit .CSV file] Add column [In reply to] Can't Post

Untested:


Code
#! /usr/bin/perl    
use strict;
use warnings;
use File::Basename;
use Text::CSV;

my $csv = Text::CSV->new();

my @files = glob("*.csv");

foreach my $file (@files) {
my $filename = $file; $filename =~ s/\.[^.]*$//;
open my $temp_fh, '>', "Temp.csv" or die "cannot open Temp.csv: $!";
open my $csv_fh, '<', "$file" or die "cannot open $file: $!";
while (my $line = <$csv_fh>) {
next if ($. == 1);
$csv->parse($line);
my @row = $csv->fields;
push (@row, $filename);
$csv->combine(@row);
my $newline = $csv->string();
print $temp_fh "$newline\n";
}
close $csv_fh;
close $temp_fh;
rename ("Temp.csv", "$file");
}


Chris


(This post was edited by Zhris on Nov 9, 2010, 9:29 PM)


srenin
New User

Nov 9, 2010, 2:31 AM

Post #3 of 4 (2199 views)
Re: [Zhris] [Edit .CSV file] Add column [In reply to] Can't Post

Thanks, that works perfectly. It creates a new column out of the full file name (example: ex1.csv as opposed to ex1).

Is there a way to make it just ex1, without the file extension?


Zhris
Enthusiast

Nov 9, 2010, 8:21 PM

Post #4 of 4 (2183 views)
Re: [srenin] [Edit .CSV file] Add column [In reply to] Can't Post

Hi,

Ah, I expected File::Basename to have split the filename from extension.

Replace:

Code
my ($filename, $filepath, $filesuffix) = fileparse($file);


With:

Code
my $filename = $file;  
$filename =~ s/\.[^.]*$//;


Which uses a regular expression instead.

Chris


(This post was edited by Zhris on Nov 9, 2010, 8:22 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives