Convert DOS to UNIX (and UNIX to DOS) in VIM

Mar 18 2013

Once upon a time I knew a vi mantra for removing carriage returns from a DOS-formatted text file, thus transforming it into a UNIX file.It was something like :%s/^V^M//g. It has become such an ingrained habit that I can still type it without even thinking about it. Muscle memory.

But VIM knows more about a file than that old clunky version of vi did, and there's an easier and more consistent way of converting between DOS and UNIX in VIM.

To convert from DOS to UNIX:

:e ++ff=dos
:setlocal ff=unix
:w

This basically forces the document into DOS mode, and then tells VIM to switch it to a UNIX file. (That closing :w just writes the change to disk.)

ff is VIM's abbreviation for fileformat. If you want to type that all out, you can. And ++? It tells VIM to effectively reopen the current file. So make sure you save your work before running these commands.

To convert from UNIX to DOS is even easier:

:e ++ff=dos
:w

That forces the file into DOS mode and then saves the change to disk.

Since both of these hook into a deeper level of VIM, they're not as prone to bugs and inconsistencies as relying upon a regular expression.

But wait... I need to do something more complicated...

The above is a great way to do simple conversions, but if your needs are more complex, you might want to take a look at the VIM wiki page in this topic.
<!--break-->