What is `^M` and how do I get rid of it?

  • When I open the file in Vim, I see strange ^M characters.

    Unfortunately, the world's favorite search engine does not do well with special characters in queries, so I'm asking here:

    • What is this ^M character?

    • How could it have got there?

    • How do I get rid of it?

    It's a control character digraph, for more info: `help digraph-table`.

    VS Code has an EOL option at the bottom that will auto convert an open file.

  • larsks

    larsks Correct answer

    9 years ago

    The ^M is a carriage-return character. If you see this, you're probably looking at a file that originated in the DOS/Windows world, where an end-of-line is marked by a carriage return/newline pair, whereas in the Unix world, end-of-line is marked by a single newline.

    Read this article for more detail, and also the Wikipedia entry for newline.

    This article discusses how to set up vim to transparently edit files with different end-of-line markers.

    If you have a file with ^M at the end of some lines and you want to get rid of them, use this in Vim:


    (Press Ctrl+V Ctrl+M to insert that ^M.)

    Try `:%s/^M/\r/g` instead to remove `^M` and replace `^M` with newline character `\r`. Without `%`, the command applies for current line only. And I came across some examples where `^M` is not at end of line, such as `The first line.^MThe second line.`

    Or if you don't want loads of line breaks you could just do `:%s/^M/`

    If it's just a carriage return by itself, that might be the classic (pre-Unix) Macintosh line break. Even some newer programs like Excel 2007 for Mac do that for some reason.

    The article to which you have linked says that `\n` is used in Unix, which is correct. That is ASCII code `10`, otherwise known as `^J`.

    Not sure if it's something in my vim config, but I have to type `Ctrl+Q`, then `Ctrl+M` to get that character to generate!

    I seem to get this character when I enter it in AWS lifecycle configurations. How do I get rid of it considering I am entering code in the cloud?

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM