I have a text file that has fixed length lines, padded by trailing spaces like:
hello world ↩
this is some other line ↩
x ↩
and I want to remove the trailing spaces on each line so it looks like
hello world↩
this is some other line↩
x↩
Is it possible to write an emacs macro that can solve this?
Edit: the lines can have any arbitrary number o开发者_运维百科f spaces in it before the trailing spaces at the end, so
hi world ↩
can be a valid line in this file.
There is an emacs command delete-trailing-whitespace
that gets rid of whitespace after last character. If you run it without any region marked, it cleans up the whole buffer. If you have an active region, only the lines in the region are cleaned.
A lot of people add the following code to their .emacs
, so that whenever they save a file, all trailing whitespace is cleaned up:
(add-hook 'before-save-hook
'delete-trailing-whitespace)
http://www.emacswiki.org/emacs/DeletingWhitespace has all you need to know.
This one is quick and works in all Emacs versions:
M-x picture-mode
, then C-c C-c
Emacs has the built-in fixup-whitespace
(M-space
), which shrinks more than one space to only one space:
hello world ↩
^
cursor
M-x fixup-whitespace
hello world ↩
^
cursor
So, you can simply define a macro that:
- first calls
fixup-whitespace
- then removes the last whitespace
Another one could be M-x replace-regexp RET [ ]+' RET ' RET
, which solves the problem using regular expressions.
I know you've already got an answer, but in addtion to fixup-whitespace
there is also delete-horizontal-whitespace
which deletes all of the whitespace around point. There are a couple of other related commands that are useful in various situations. You can look them up with M-: (info "(elisp) User-Level Deletion")
.
精彩评论