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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove trailing space from fields of CSV file 1

Status
Not open for further replies.

rzs0502

IS-IT--Management
Nov 18, 2002
708
Hi All,

I am quite new to Perl and I have the following problem.
I have several comma separated csv files that I need to remove the trailing spaces from each field.
File Eg.

abc ,Some ABC text ,123456 ,data
xyz ,Some XYZ text ,567890 ,data2

What would be the best way to remove the trailing spaces of each field?

Many thanks.


"If you always do what you've always done, you will always be where you've always been."
 
Code:
perl -pi.bak -e "s/\s+,/,/g; s/\s+$//;" file.csv

- Kevin, perl coder unexceptional!
 
Excellent!
Thanks Kevin!
Any way I can preserve the end of line character with your method.
It has created a file with one long line of text.

Thanks again...


"If you always do what you've always done, you will always be where you've always been."
 
Hi Kevin,

From your help I've done this...

Code:
#!/usr/bin/perl -w

$file_name = "/admin/tmp/TRA.CSV";
$new_file = "${file_name}.NEW";

open (DATFILE,"< $file_name") or die "Cannot open $file_name\n";
open (NEWFILE,"> $new_file") or die "Cannot write to ${new_file}";
foreach $entry (<DATFILE>) {
    $entry =~ s/\s+,/,/g;
    print NEWFILE $entry;
}
close DATFILE;
close NEWFILE;

Output seems correct, but is the code 'proper' Perl?

Thanks very much!


&quot;If you always do what you've always done, you will always be where you've always been.&quot;
 
rzs0502
You can modify your code for better by using strict.Initially it may give you complie errors. You have to remove them by declaring variables using appropriate scope(e.g.my)
Remove a newline character using chomp(), after you read the file line by line.
Also
${file_name} can be safely replaced by $file_name.Same with
${new_file}.


--------------------------------------------------------------------------
I never set a goal because u never know whats going to happen tommorow.
 
Just do mine like this:

Code:
perl -pi.bak -e "s/\s+,/,/g" file.csv

or if you wanted to output to the .NEW file:

Code:
perl -pe "s/\s+,/,/g" /admin/tmp/TRA.CSV > /admin/tmp/TRA.CSV.NEW


this is much more efficient than your method but your method is fine and the code is good. As spookie mentions, using "use strict" is recommended for all perl progams.

- Kevin, perl coder unexceptional!
 
Thanks very much guys!
Useful info!


&quot;If you always do what you've always done, you will always be where you've always been.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top