Easy incrementing find and replace in emacs

I start with a list with a bunch of entries like this:

newsletter W02

newsletter W02

newsletter W02

newsletter W02

EDIT: New Solutions

It turns out that emacs automatically initializes a variable that tracks how many interations your replacement function has made, and in lisp mode you can get to it with \#. This way, the single line necessary to number all my newsletters becomes this:

W\(02\) → W\,(format "%02d" (+ 4 \#)))

and, of course, you can adjust that 4 to whatever you need it to be for your starting digit.

Old Solution

A new solution is shown above that makes this process a one-liner; the solution below with setting up your own variable is kept for reference.

After running (setq w 1) to initialize before editing a list of 52 items that each had “W02” at line-end, I ran the following to make them a counting list from 2 to 52:

W02  W\,(format "%02d" (setq w (1+ w)))

In practice, you use replace-regexp, enter the W02, then press enter instead of the arrow and then type the remainder in. The \,(format "%02d" ...) indicate that we are going to produce 0-padded numbers, so once we get to double digits there will be no zero. Then you see the final setq which increments and feeds format our count variable.

Take care that on stateful changes like this (stateful because we are using a variable w to keep track of our week number), you can’t use a previewing replacement like anzu-query-replace-regexp because the previews themselves will increment your variable. So just use plain replace-regexp.

In the end you have:

newsletter W02

newsletter W03

newsletter W04

newsletter W05

Tory Anderson avatar
Tory Anderson
Digital Humanist, Web App Engineer, PhD Candidate, Computer Psychologist
comments powered by Disqus