What do you do if you don’t have dos2unix, need to convert a file or three from DOS (or Mac) format to UNIX format, but all you have is Emacs? Well, of course you use Emacs for the file conversion, what else?

I’ve blogged before about getting rid of those pesky ^M characters using Emacs, but that’s of use for mixed format files – for example when someone checked in a file without setting something like git’s autocrlf configuration setting first. This post deals with converting a complete file that ended up in the wrong format.

Turns out it’s actually surprisingly easy because Emacs has a command for that.

set-buffer-file-coding-system allows you to change the file encoding and the line endings with a simple command. To achieve the dos2unix style conversion, simply passing unix as the parameter does the job, but a quick look at the available parameters shows that you can also set the text encoding for a buffer (utf-8, utf-16 et al). Please note I haven’t had a chance to verify that the change of encoding also converts the existing text, although I strongly suspect it does.

Anyway, here you have it – a simple replacement for dos2unix and it can also do so much more.

1 thought on “Converting files from DOS to UNIX file formats using Emacs

Leave a Reply