Getting rid of the ^M characters in vi

If you’re a regular vi user, you may have noticed that some files, when being edited in vi, contain ^M characters at line ends.

This usually happens when you edit a file using certain windows-editors, then transfer it to your *nix machine.
Luckily, it is easily to get rid of this control character. While in vi, execute the following command:

:1,$s/^M//g

Important note: do not manually type a caret then the capital M character. Actually, in order to type ^M, press CTRL+V followed by CTRL+M.

A quick note:  the above command will look for the ^M character starting on line 1, replacing it ($s) with nothing (thus having the two consecutive forward slashes / with nothing in between). And this replacement is done globally (g).

4 Comments

Prosthetic LipsJanuary 21st, 2011 at 10:26 PM

Um … just a note, your explanation of the $ is wrong.

1,$ means “lines 1 through the end of the file”
s means “search and replace” (or some such nonsense)
g technically means “do it through the whole line” (otherwise it just does the first time it finds it)
the rest of your explanation was spot-on. But, for example, you could say:

3,15s/^M//

to mean, replace all occurrences on lines 3 through 15. The “g” probably doesn’t matter to you, because you only get one per line anyway.

~Prosthetic Lips

adminJanuary 31st, 2011 at 8:20 AM

cheers

LTCJanuary 6th, 2012 at 10:40 AM

s means “substitute” not “search and replace”. And it isn’t nonsense.
Searching, of course, is achieved using with the forward slash / character.

Prosthetic lips | FindcdsJanuary 26th, 2012 at 1:17 AM

[...] Tips and Tricks » Blog Archive » Getting rid of the ^M characters in viJan 1, 2009 … Prosthetic LipsJanuary 21st, 2011 at 10:26 PM. Um … just a note, your explanation of the $ is wrong. 1,$ means “lines 1 through the end of the … [...]

Leave a comment

Your comment