emacs – Removing the Last n Characters from Every Line in an Emacs Buffer

emacs

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:

  1. Since XEmacs is mostly dead (RIP), the question can be assumed to be
    exclusively about GNU Emacs.

  2. There are easy solutions for this using Unix stream editors and the like.
    Operating on an Emacs buffer is more flexible, though.

  3. 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:

M-< M-x replace-regex RET .$ RET RET

To replace multiple chars, you can, in a pedestrian fashion, start prepending .? (one optional any-char) to your regex:

M-< M-x replace-regex RET .?.$ RET RET

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:

M-< M-x replace-regex RET \{,2\}$ RET RET

There's more on regex syntax under RegularExpression at EmacsWiki