Dos2unix in Emacs, Sometimes Macros Are Nice

No CRLF
This is just a generic search and replace. Really you could make a macro for any search and replace you do on a regular basis.

;;; A interactive function for replacing all dos
;;; carriage returns (^M) with Unix 
;;; line feeds in a selected buffer. 
(defun dos2unix (buffer)
  "Automate M-% C-q C-m RET C-q C-j RET"
  (interactive "b buffer to convert" )
  (goto-char (point-min))
  (while (search-forward (string ?\C-m) nil t)
    (replace-match "" nil t)))
  • Linux and Systems
. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “Dos2unix in Emacs, Sometimes Macros Are Nice”

  1. Hagen Says:

    Not to be a smart ass, but the function doesn’t do what it says in the description. It replaces the ^M with nothing, not with ^J. For most files this is fine, since the ^M appears at the end of the line. If the ^M is immersed in the lines you have to (replace-match (string ?\C-j) nil t) of course. In the file I needed this for (thank you for your function as my starting point), both cases appeared. So I solved it inelegant but pragmatic this way:

    (defun dos2unix (buffer)
    (interactive “b buffer to convert” )
    (goto-char (point-min))
    (while (search-forward (string ?\C-m?\C-j) nil t)
    (replace-match (string ?\C-j) nil t))
    (goto-char (point-min))
    (while (search-forward (string ?\C-m) nil t)
    (replace-match (string ?\C-j) nil t)))

  2. A R Baboon Says:

    The Microsoft line ending is prepends each line feed with a carriage return. All we want to do strip out any carriage returns. I would say that we should do a more sophisticated pattern match for line ending, etc., but I am not sure there should ever be carriage returns in a file.

  3. A R Baboon Says:

    It would be good to save and restore the point for convenience. Also a unix2dos has now become useful for diff/cvs interactions.

Leave a Reply


Bad Behavior has blocked 144 access attempts in the last 7 days.