How do I remove Windows carriage returns (^M) from a file opened in Vim?
Answer
:%s/\r//g
Explanation
When a file created on Windows is opened in Vim on a Unix system, lines may retain \r (carriage return) characters, displayed as ^M at the end of each line. This happens when Vim's fileformat detection fails or the file is transferred without conversion. The substitute command :%s/\r//g removes all carriage returns instantly.
How it works
%— addresses every line in the buffers/\r//g— substitutes every carriage return (\r, ASCII 0x0D) with nothing; thegflag applies the substitution to all occurrences on each line
Example
Before (displayed with :set list):
first line^M
second line^M
third line^M
After running :%s/\r//g:
first line
second line
third line
Tips
- An alternative:
:set fileformat=unixfollowed by:w— Vim strips\rautomatically on write. This also updates Vim's internalfileformatsetting for the buffer - To detect the problem without
:set list, run:set ff?— if it showsfileformat=dos, the file has Windows line endings - The
:set listoption reveals hidden characters;^Mappears at line ends in DOS-format files - To convert the other direction (Unix to Windows), use
:set fileformat=dos | w