5

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.

  • I don't speak emacs, but I'm sure that there's an analog for the way to do this in vim, which would be %s/.....$// – DopeGhoti Jan 8 '14 at 20:31
4

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

  • Thanks. Can you put in where n goes in the expression? – Faheem Mitha Jan 8 '14 at 20:30
  • Updated to include multiple chars. – R Perrin Jan 8 '14 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.