Getting rid of ^M (Ctrl-M) characters in Windows text using Vim

Text files created on Microsoft Windows usually use a combination of Carriage-Return and New-Line (CR-LF or \r\n) to separate lines.

When such text files are opened in Windows using Vim (usually in the Unix mode), the Carriage-Return’s will show up in the file as ^M (CTRL-M) and can be annoying specially when you are going through long text files. Note that though the ^M has two characters, Vim treats them as a single visible control character.

You can delete the ^M’s by moving the cursor over the caret and pressing ‘x’ in the command mode. Alternately, you can use Vim’s substitute command (used for search and replace) to remove all the ^M (CTRL-M) characters in one fell swoop.

To do the substitute action, in command mode, press “:” (colon, without the quotes) to start entering text on the mode-line at the bottom of the window.

Then, enter “1,$s/^M//g” (without the double-quotes) on the mode-line and press Enter. Presto, all your ^M’s are gone.

Do not enter the ^M in the above as a ‘^’ (caret) followed by an ‘M’. Instead, when it is time to enter this character, first press CTRL-Q to enter a mode where control characters can be keyed in and then press CTRL-M. This will actually insert the ^M (CTRL-M) as a special control character with the caret and the M (and which is treated like a single character though visibly it’s two characters).

To summarize, in command mode, type in the following

:
1
,
$
s
/
CTRL-Q
CTRL-M
/
/
g
ENTER

Share
This entry was posted in Uncategorized and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Related Posts:

4 Comments

  1. David Wong
    Posted November 24, 2010 at 12:41 pm | Permalink

    Thanks so much for this hint.

    I was able to use and to build the ^M character on my Windows PC running Vim 6.4. However, is somehow mapped to paste on Linux PC running Vim 7.2 and this trick is what I’ve been looking for.

  2. David Wong
    Posted November 24, 2010 at 12:59 pm | Permalink

    Do you know why this trick works with gvim but not vim?

  3. Posted November 28, 2010 at 10:08 am | Permalink

    That’s probably because the key-combo to enter a control character may be different. Try ^V instead of ^Q.

  4. lken
    Posted November 17, 2011 at 10:52 am | Permalink

    thanks you! finally I know how to get rid of ^M !

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*