Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding a comma to the end of each line

Status
Not open for further replies.

ianicr

IS-IT--Management
Nov 4, 2003
230
GB
Is there an easy way to add a comma to the end of each line of a csv file?
 
If you are talking about creating a new csv, then just put it there in your print statement. If you are talking about an existing csv, then read the file in and print it back out with a comma appended to the end.

open (IN, $file);
open (OUT, >$temp);
while (<IN>) {
print OUT &quot;$_,\n&quot;;
}
close (IN);
close(OUT);

unlink ($file);
rename ($temp, $file);
 
I believe in the above sample, you would need to chomp the $_ firat or you would end up with a comma on its own line. I would do it this way:

open (IN, $file);
open (OUT, >$temp);
while (<IN>) {
s/\n/,\n/;
print OUT;
}
close (IN);
close(OUT);

unlink ($file);
rename ($temp, $file);
 
>> you need to chomp the $_ first

Yeah, that is right.

open (IN, $file);
open (OUT, >$temp);
while (<IN>) {
chomp;
print OUT &quot;$_,\n&quot;;
}
close (IN);
close(OUT);

unlink ($file);


The regex substitution works also, but I think it is a more expensive operation to do.
rename ($temp, $file);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top