In emacs, how to strip CR (^M) and leave LF (^J) c

2019-03-09 05:26发布

I am trying to use hexl mode to manually remove some special chars from a text file and don't see how to delete anything in hexl mode.

What I really want is to remove carriage return and keep linefeed characters. Is Hexl mode the right way to do this?

9条回答
小情绪 Triste *
2楼-- · 2019-03-09 05:36

From http://www.xsteve.at/prg/emacs/xsteve-functions.el:

;02.02.2000
(defun xsteve-remove-control-M ()
  "Remove ^M at end of line in the whole buffer."
  (interactive)
  (save-match-data
    (save-excursion
      (let ((remove-count 0))
        (goto-char (point-min))
        (while (re-search-forward (concat (char-to-string 13) "$") (point-max) t)
          (setq remove-count (+ remove-count 1))
          (replace-match "" nil nil))
        (message (format "%d ^M removed from buffer." remove-count))))))

Add this to your .emacs and run it via M-x xsteve-remove-control-M or bind it to a easier key. It will strip the ^Ms in anymode.

查看更多
神经病院院长
3楼-- · 2019-03-09 05:38

You don't need to use hexl-mode. Instead:

  • open file in a way that shows you those ^M's. See M-x find-file-literally /path/to/file above. In XEmacs you can also do C-u C-x C-f and select binary encoding.
  • select the string you want replace and copy it using M-w
  • do M-% (query replace) and paste what you want to copy using C-y
  • present Enter when prompted to what replace it with
  • possible press ! now to replace all occurrences

The point is that even if you don't how to enter what you are trying to replace, you can always select/copy it.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-03-09 05:42

Assuming you want a DOS encoded file to be changed into UNIX encoding, use M-x set-buffer-file-coding-system (C-x RET f) to set the coding-system to "unix" and save the file.

查看更多
Ridiculous、
5楼-- · 2019-03-09 05:43

If you want to remove a carriage return (usually displayed as ^M) and leave the line feed. You can just visit the file w/out any conversion:

M-x find-file-literally /path/to/file

Because a file with carriage returns is generally displayed in DOS mode (hiding the carriage returns). The mode line will likely display (DOS) on the left side.

Once you've done that, the ^M will show up and you can delete them like you would any character.

查看更多
老娘就宠你
6楼-- · 2019-03-09 05:47

Oops. That ^J^M needs to be entered as two literal characters. Use c-q c-j, c-q c-m and for the replacement string, use c-q c-j.

查看更多
放我归山
7楼-- · 2019-03-09 05:53

No need for hexl-mode for this. Just do a global-search-and-replace of ^J^M with ^J Works for me. :) Then save the file, kill the buffer, and revisit the file so the window shows the new file mode (Unix vs DOS).

查看更多
登录 后发表回答