Removing the ^M (carriage return) character from text files
4 August 2007 – 12:13 am by wg
I came across this problem again tonight editing a theme file for this site — the annoying ^M carriage return character that gets added to the end of lines of files that have been edited by someone at some time with a Windows text editor. This has been one of my pet hates for years.
There are two ways to remove these characters:
From within vi:
:%s/^M//g
(hold down Ctrl+V and then Ctrl+M to get the ^M character)
From the command line:
tr -d '\r' < filename > filename.new ; mv filename.new filename
(yes, the < and > are meant to be there)


























6 Responses to “Removing the ^M (carriage return) character from text files”
Actually, I think you may have missed something for the children.
You need to first v then m, holding the control button down hitting the v then holding the control button down hitting the m. Else, at least in my tcsh shell, it won’t type the ^M properly (in a useful format).
By JasonN on Aug 15, 2007
Quite right you are, JasonN! I will update the post to reflect that. Thanks for pointing out my omission.
By wg on Aug 15, 2007
Here’s my favorite PERL one-liner..
perl -pi -e ’s/\cM//’ filename.ext
By Andryan on Mar 24, 2008
That little Perl snippet was a lifesaver, thanks!!
By Tom W on Oct 8, 2008
Easiest is to use dos2ux filename > newfile
By Markus on Apr 8, 2009
What does the perl -pi -e ’s/\cM//’ filename.ext line do? I can’t seem to find any information on any of the tags (ex. -pi -e).
Thanks!
By Salar E on Sep 3, 2010