emacs - replace numbers with calculated numbers

To replace numbers in a document with other calculated numbers (e.g. to replace a 20 with 20-10=10, and a 43 with 33), the best is to use

M-x query-replace-regexp

which is bound to

M-C-%  (= M-C-Shift-5).

Or use

M-x replace-regepx

E.g. to subtract 8 from each number in  the string

out_11_14Small.png

do the following:

M-x query-replace-regexp
[Query replace regexp:] \([0-9][0-9]\) RET
[Query replace regexp in region \([0-9][0-9\) with:]   \,(+ -8 \#1) RET

RET = press the return key.

You get

out_3_6Small.png.

Explanation

\([0-9][0-9]\)  matches each expression which has two numbers, like 11, 03, 53 etc.

The \( \) brackets mean, that the two digits form a group.

In the replace string \, says that a Lisp expression follows, + does a incrementation by -8 (so subtracts 8).

\#1 will be replaced by the first match (the two digits), interpreted as a number (hence the #). Without the #, so just \1, it will be interpreted as a string.

blog_tags: 

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <img> <br> <p> <span>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Use [collapse] and [/collapse] to create collapsible text blocks. [collapse collapsed] or [collapsed] will start with the block closed.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Code snippets in <code>...</code> or <source>...</source> automatically will be pretty printed.
  • Use [collapse] and [/collapse] to create collapsible text blocks. [collapse collapsed] or [collapsed] will start with the block closed.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Target Image