How to use emacs to replace Mac carriage returns (the ^M line endings, and that includes even the “stubborn” ones!)…

The below information was shamelessly copied, word for word, from http://mike.kruckenberg.com 🙂

Changing end-of-line Mode in Emacs (replaces ^M line return)

Every now and then I run into this. I export CSV data from Excel and find that when trying to use it in other places the line-returns aren’t quite right and unix tools like ‘less’ and ‘pico’ think the file is one long line, with ^M in places where a line-return should be.

Wanting to replace the ^M I open the file in emacs, which is smart enough to go into Mac mode and show the file with the correct line returns.

I poked around and found that if the ^M is showing up in emacs this sequence will replace them:
1. M-% (esc % on Mac X11 Emacs)
2. ctrl-q ctrl-m RET (specifies ^M to replace)
3. ctrl-q ctrl-j RET (specifies a line return as the replacement)
4. ! (runs the replace on the entire file)

But in my case the ^M isn’t showing because emacs knows to use ^M for a line return on mac. So what I need to do is change the end-of-line, which is specified in buffer-file-coding-system. You can change the file from Mac mode to unix with this command:

M-x set-buffer-file-coding-system RET unix

When you do that emacs suggests using this shortcut:

ctrl-x RET f unix RET

Save the file after changing the end-of-line and all is good in my other unix utilities.

One thought on “How to use emacs to replace Mac carriage returns (the ^M line endings, and that includes even the “stubborn” ones!)…

  1. … or …
    Just use dos2unix / unix2dos commands to fix the EOL characters in the file to your liking.

    … or …
    You can change file’s encoding to e.g. ‘unix’ with

    M-x set-buffer-file-coding-system

    .. or its shortcut Ctrl-X, f, like this

    C-x RET f unix

Leave a Reply to Alan Cancel reply

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