What is `^M` and how do I get rid of it?
When I open the file in Vim, I see strange
Unfortunately, the world's favorite search engine does not do well with special characters in queries, so I'm asking here:
What is this
How could it have got there?
How do I get rid of it?
^Mis 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.
This article discusses how to set up vim to transparently edit files with different end-of-line markers.
If you have a file with
^Mat 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
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.`
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.
@larsks But https://www.altap.cz/salamander/help/salamand/appendix_txtfiles/ says that `^M` is used in UNIX
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!