14

How can I remove ^M characters in Emacs?

It doesn't work using dos2unix filename or unix2dos filename.

Normally I cannot see any ^M characters, but this is what came out when using the command cat -A filename :

Please explain it in plain words... and in detail...

cat -A ABC.sh
#!/bin/csh -f^M$
^M$
^M$
set input = `ls -1 *.py`^M$
echo $input^M$
Henke
  • 4,445
  • 3
  • 31
  • 44
user3647551
  • 141
  • 1
  • 3

2 Answers2

26

[Searched for a duplicate, but didn't find one about replacing (instead of preventing etc.). If there is one then this one or that one should be closed.]

In Emacs, visit the file that has the ^M chars. Go to the beginning of the file (M-<), then:

M-x replace-string RET C-q C-m RET RET

That is, at the prompt for what to replace, use Control + q then Control + m, then Enter. At the prompt for what to replace it with, just hit Enter (replace it with nothing).

Drew
  • 29,895
  • 7
  • 74
  • 104
  • Thanks. This worked fine, however there must be a `RET` between `replace-string` and `C-q` – Ytrog Jul 09 '22 at 07:57
  • this actually didn't work for me, the command was identified correctly replacing ^M with "", but 0 occurrences were replaced – Aiden Cullo Feb 07 '23 at 16:28
  • @AidenCullo: Does your buffer actually contain `^M` chars? What does `C-s C-q C-m` show you? – Drew Feb 07 '23 at 18:17
8

I've been using this

(defun delete-carrage-returns ()
  (interactive)
  (save-excursion
    (goto-char 0)
    (while (search-forward "\r" nil :noerror)
      (replace-match ""))))

I'm sure there is a better way, but this works well enough that I stopped looking.

michaelJohn
  • 679
  • 5
  • 9
  • This helps when ^M gets pasted form clipboard. Then, other systems wiill not work. – gsl Feb 10 '23 at 13:15