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
4 Comments
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.
Do you know why this trick works with gvim but not vim?
That’s probably because the key-combo to enter a control character may be different. Try ^V instead of ^Q.
thanks you! finally I know how to get rid of ^M !