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, substituting it ($s) with nothing (thus having the two consecutive forward slashes / with nothing in between). And this substitution is performed globally (g).

3 Responses to “Getting rid of the ^M characters in vi”

  1. LTC says:

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

  2. admin says:

    cheers

  3. Prosthetic Lips says:

    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

Leave a Reply