Repost – how to get rid of those pesky ^M characters using Emacs

By | July 28, 2013

I had another of these annoying mixed-mode DOS/Unix text files that suffered from being edited in text editors that didn’t agree which line ending mode they should use. Unfortunately Emacs defaults to Unix text mode in this case so I had an already ugly file that wasn’t exactly prettified by random ^M characters all over the place.

Another repost from the old blog.

I also don’t have the cygwin tools on the machine that I was seeing this problem on, I couldn’t just run unix2dos or dos2unix over the file and be done with it, but at least I had emacs on that machine. So, emacs to the rescue again…

First, I used query-replace to get rid of the ^Ms in so the file was turned into a “proper” Unix text file. The trick here is that you need to use control-Q to quote the control character. In my case on a Windows box, the key sequence was M-Shift-% Control-Q Control-M and then use the empty string as a replacement value. Job done, we’ve now got a proper Unix mode text file. Well, after almost wearing out the ‘Y’ key but of course you can use replace-string instead.

In order to turn the Unix mode text file into a Dos mode one, run the command set-buffer-file-coding-system with the parameter undecided-dos and save the resulting file. Job done.

4 thoughts on “Repost – how to get rid of those pesky ^M characters using Emacs

  1. Adam

    Instead of wearing out your y key, you can press ! once, to say yes to replace the remaining matches :-)

    Reply
    1. Timo Geusch Post author

      Thanks, learned something new! Admittedly I’m a little paranoid when using search & destroy, err, replace so I tend to want to review all the changes the editor would make. With modern source control and the undo support modern editors have that’s admittedly a little unnecessary these days.

      Reply
  2. icarus

    Not sure why you want to waer out the “Y” key, just press “!” and it does the rest of the (visible) buffer for you.

    Reply
  3. George

    If you are worry about unintended changes using ‘!’, you could diff the file against the original one afterwards to make certain the changes are good. If they aren’t, revert to the original file and start again.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *