How to remove ^M in emacs [duplicate]
Asked Answered
A

2

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$
Atrocious answered 17/5, 2014 at 13:47 Comment(1)
dos2unix should convert that. What output does it give you?Ad
G
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).

Gonzales answered 17/5, 2014 at 14:33 Comment(3)
Thanks. This worked fine, however there must be a RET between replace-string and C-qInterrupter
this actually didn't work for me, the command was identified correctly replacing ^M with "", but 0 occurrences were replacedFascicle
@AidenCullo: Does your buffer actually contain ^M chars? What does C-s C-q C-m show you?Gonzales
S
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.

Sumikosumma answered 18/5, 2014 at 19:3 Comment(1)
This helps when ^M gets pasted form clipboard. Then, other systems wiill not work.Bluejacket

© 2022 - 2024 — McMap. All rights reserved.