Using Emacs built-in facilities, is there a good way to remove the last n characters (for n >= 1) from every line in an Emacs buffer? I suppose it is possible to define a keyboard macro to do this, but that is not what I have in mind here.
There is an elegant solution on Stack Overflow to the corresponding question of how to append characters to every line in emacs, namely
Appending characters to the end of each line in Emacs,
but I could not find an answer to this question.
NOTES:
-
Since XEmacs is mostly dead (RIP), the question can be assumed to be
exclusively about GNU Emacs. -
There are easy solutions for this using Unix stream editors and the like.
Operating on an Emacs buffer is more flexible, though. -
I could of course do this by hand, but I've made a sort-of New Year
resolution to make better use of Emacs capabilties. After all, I've been
using it a mere 20 years, and know almost nothing about it.
Best Answer
You can use the same replace-regex approach to remove as the append case, just prefix the end-of-line regex meta-character with an any-character meta-character:
To replace multiple chars, you can, in a pedestrian fashion, start prepending
.?
(one optional any-char) to your regex:or, more elegantly, you can use in interval-style notation to indicate up to
n
any-chars before the end-of-line, in the following example, n=2:There's more on regex syntax under RegularExpression at EmacsWiki