Convert DOS line endings to Linux line endings in Vim

If I open files I created in Windows, the lines all end with ^M. How do I delete these characters all at once?


dos2unix is a commandline utility that will do this, or :%s/^M//g will if you use Ctrl-v Ctrl-m to input the ^M, or you can :set ff=unix and Vim will do it for you.

There is documentation on the fileformat setting, and the Vim wiki has a comprehensive page on line ending conversions.

Alternately, if you move files back and forth a lot, you might not want to convert them, but rather to do :set ff=dos, so Vim will know it's a DOS file and use DOS conventions for line endings.


Change the line endings in the view:

:e ++ff=dos
:e ++ff=mac
:e ++ff=unix

This can also be used as saving operation (:w alone will not save using the line endings you see on screen):

:w ++ff=dos
:w ++ff=mac
:w ++ff=unix

And you can use it from the command-line:

for file in *.cpp
do 
    vi +':w ++ff=unix' +':q' "$file"
done

I typically use

:%s/\r/\r/g

which seems a little odd, but works because of the way that Vim matches linefeeds. I also find it easier to remember :)


I prefer to use the following command:

:set fileformat=unix

You can also use mac or dos to respectively convert your file to Mac or MS-DOS/Windows file convention. And it does nothing if the file is already in the correct format.

For more information, see the Vim help:

:help fileformat

:set fileformat=unix to convert from DOS to Unix.