views:

4745

answers:

8

Hi! I have a script that is appending new fields to an existing CSV, however ^M characters are appearing at the end of the old line so the new fields end up on a new row instead of the same one. How do you remove the ^M characters from a csv file using Perl?.

+8  A: 

^M is carriage return. You can do this:

$str =~ s/\r//g
Can Berk Güder
+1  A: 

To convert DOS style to UNIX style line endings:

for ($line in <FILEHANDLE>) {
   $line =~ s/\r\n$/\n/;
}

Or, to remove UNIX and/or DOS style line endings:

for ($line in <FILEHANDLE>) {
   $line =~ s/\r?\n$//;
}
spoulson
wouldn't that remove the newlines, too?
Can Berk Güder
I guess that depends on your goal. I edited to show both strategies.
spoulson
+6  A: 

Or a 1-liner:

perl -p -i -e 's/\r\n$/\n/g' file1.txt file2.txt ... filen.txt
JDrago
It's so easy to remember this one as Perl Pie.
dreamlax
@dreamlax: haha perl pie!
+5  A: 

You found out you can also do this:

$line=~ tr/\015//d;

Alex Wong
A: 

Can't you just chomp it?

chomp($str)
Perchik
A: 

In vi hit :

then s/Contrl-VControl-M//g

control-v control-m are obviously those key's dont' spell it out.

+1  A: 

slightly unrelated, but to remove ^M from the command line using perl, do this

perl -p -i -e "s/\r\n/\n/g" file.name
Roy Rico
A: 

What if I had a record in a otherwise good file that had a carriage return in it.

Ex:

1,2,3,4,5 ^M

,6,7,8,9,10

and I wanted to make it

1,2,3,4,5,6,7,8,9,10

Dan
Hello Dan, welcome to Stack Overflow. You asked a question in the answer field, but this site does not work this way. To give your problem the appropriate attention, please [open a new question](http://stackoverflow.com/questions/ask). You can delete [your initial posting](http://stackoverflow.com/questions/650743#3213976) later. Take the time to familiarise yourself with [how SO works](http://stackoverflow.com/faq).
daxim