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?.
+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
2009-03-16 14:51:33
wouldn't that remove the newlines, too?
Can Berk Güder
2009-03-16 14:54:27
I guess that depends on your goal. I edited to show both strategies.
spoulson
2009-03-16 15:23:41
+6
A:
Or a 1-liner:
perl -p -i -e 's/\r\n$/\n/g' file1.txt file2.txt ... filen.txt
JDrago
2009-03-16 16:36:04
+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
2009-03-16 17:45:32
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
2010-07-09 15:14:12
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
2010-07-09 15:39:03