Brein
Brein

Reputation: 55

Adding headers in csv perl

I need to add headers in to an exsisting CSV file. i'm new to perl so i've got no clue hwo to do it so if i can get some guidense from yuo awesome ppl it would be.

awesome ^.^

The CSV file layout is as follows.

header: name, function, group, 
data:   Henk, Kok,      B,     

header: name, function, group, password
data:   Henk, Kok,      B,   , 1234

Upvotes: 1

Views: 2181

Answers (2)

slayedbylucifer
slayedbylucifer

Reputation: 23492

I need to add headers in to an exsisting CSV file

Why not use use this simple one-liner than writing a full fledged program...

$ sed -i '1i name, function, group' CSV_FILE_NAME

and here is perl way of doing it:

$ perl -pi -e 'print "name, function, group\n" if $. == 1' CSV_FILE_NAME

Upvotes: 0

Needpoule
Needpoule

Reputation: 4576

You can probably do something like that:

open(FILE,'<',"myfile.csv");
open(NEW_FILE,'>',"myfile.new.csv");
#You header
print NEW_FILE "name, function, group\n";
my $line;
while( $line = <FILE> ) {
    print NEW_FILE $line;
}
close NEW_FILE;
close FILE;

From the Perl FAQ : http://perldoc.perl.org/perlfaq5.html#How-do-I-change,-delete,-or-insert-a-line-in-a-file,-or-append-to-the-beginning-of-a-file?

Upvotes: 2

Related Questions