Removing the ^M (carriage return) character from text files

4 August 2007 – 12:13 am by wg

Removing the ^M (carriage return) character from text filesI 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)


del.icio.us:Removing the ^M (carriage return) character from text files  digg:Removing the ^M (carriage return) character from text files  spurl:Removing the ^M (carriage return) character from text files  wists:Removing the ^M (carriage return) character from text files  simpy:Removing the ^M (carriage return) character from text files  newsvine:Removing the ^M (carriage return) character from text files  blinklist:Removing the ^M (carriage return) character from text files  furl:Removing the ^M (carriage return) character from text files  reddit:Removing the ^M (carriage return) character from text files  fark:Removing the ^M (carriage return) character from text files  blogmarks:Removing the ^M (carriage return) character from text files  Y!:Removing the ^M (carriage return) character from text files  smarking:Removing the ^M (carriage return) character from text files  magnolia:Removing the ^M (carriage return) character from text files  segnalo:Removing the ^M (carriage return) character from text files  gifttagging:Removing the ^M (carriage return) character from text files

Possibly related posts

  1. 6 Responses to “Removing the ^M (carriage return) character from text files”

  2. 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

  3. 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

  4. Here’s my favorite PERL one-liner..
    perl -pi -e ’s/\cM//’ filename.ext

    By Andryan on Mar 24, 2008

  5. That little Perl snippet was a lifesaver, thanks!!

    By Tom W on Oct 8, 2008

  6. Easiest is to use dos2ux filename > newfile

    By Markus on Apr 8, 2009

  7. 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

Post a Comment