ViM 7 Tip: Getting rid of ^M

It’s been over 15 months since I moved to Mac (Unix-based) OS. Not too often but I still have to modify code that I wrote during my Windows days. The most common problem opening a DOS-formatted text file (PHP file in this case) is getting a ^M at the end of every line. Which looks something like this:

Vim 7 ^M problem

And here is how to get rid of them:

:%s/^M$//g

BE SURE YOU MAKE the ^M USING “CTRL-V CTRL-M” NOT BY TYPING “CARET M”! This expression will replace all the ^M’s that have carriage returns after them with nothing. (The dollar ties the search to the end of a line)



This entry was posted on Thursday, January 4th, 2007 at 12:18 pm and is filed under Technology, Work @ Tenmiles. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

5 Responses to “ViM 7 Tip: Getting rid of ^M”

  1. A says:

    Shalin bhai,

    A simple :%s/$//g will also do the trick. And BTW, it is caret and not carrot

  2. shalinjain says:

    Thanks @A.

    “CARROT M” phrase – which I quoted comes from the official ViM tips section – http://www.vim.org/tips/tip.php?tip_id=26 – I did a quick copy paste then – I have fixed it on my blog at least.

  3. shalinjain says:

    :%s/$//g – Didn’t work for me!

  4. bub says:

    @shalinjain:

    “:%s/$//g” won’t work of course because it replaces your endofline, so probably, replacing a non-^M characters.

  5. Karl Bielefeldt says:

    Really old post, but still highly ranked on a search. You probably want :%s/.$//

    The dot means it will replace the last character before the end of the line, which is the ^M.

Leave a Reply