How to remove ^M
characters in Emacs?
It doesn't work using dos2unix filename
or unix2dos filename
.
This is what came out when I using command cat -A filename
because normally I cannot see ^M
characters.
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$
Although emacs has sophisticated features, the basics are easy to learn. Ordinary characters that are typed are put directly into the text. Commands to emacs are given by control characters (denoted C-) and Meta characters (denoted M-). For example, C-f would be entered by holding down the Ctrl key while typing f.
A: The “^M” is ASCII caret notation for unprintable Carriage return char (ASCII 13).
Modern versions of emacs know how to handle both UNIX and DOS line endings, so when ^M shows up in the file, it means that there's a mixture of both in the file. When there is such a mixture, emacs defaults to UNIX mode, so the ^Ms are visible.
Modern versions of emacs know how to handle both UNIX and DOS line endings, so when ^M shows up in the file, it means that there's a mixture of both in the file. When there is such a mixture, emacs defaults to UNIX mode, so the ^Ms are visible. The real fix is to fix the program creating the file so that it uses consistent line-endings.
The following are different options to remove, convert or translate the ^M characters: Note: To enter ^M, type CTRL-V + M. That is, hold down the CTRL key then press V and M in succession. Then save and close the file. File has been transferred between systems of different types with different newline conventions.
I made a file that has two lines, with the second having a carriage return. Emacs would open the file in Unix coding, and switching coding system does nothing. However, the universal-coding-system-argument above works.
[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 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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With