vimtricks.wiki Concise Vim tricks, one at a time.

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 buffer
  • s/\r//g — substitutes every carriage return (\r, ASCII 0x0D) with nothing; the g flag 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=unix followed by :w — Vim strips \r automatically on write. This also updates Vim's internal fileformat setting for the buffer
  • To detect the problem without :set list, run :set ff? — if it shows fileformat=dos, the file has Windows line endings
  • The :set list option reveals hidden characters; ^M appears at line ends in DOS-format files
  • To convert the other direction (Unix to Windows), use :set fileformat=dos | w

Next

How do I generate multiple lines of text using a Vimscript for loop from the command line?