16

Let us say I have a text like so below:

AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)
AC(nn)

Now I want to replace the nn with numbers like so

AC(0)
AC(1)
AC(2)
AC(3)
AC(4)
AC(5)
AC(6)
AC(7)
AC(8)
AC(9)
AC(10)

I used M-x replace-regexp nn RET \# RET to accomplish this.

Questions:

  1. I want to start the replacement number to start from 1 rather than from 0. Or rather start from a specified number say 25. How should I modify the above command?
  2. How to replace nn with digits like 001, 002 .... 998, 999etc - I mean with leading zeros
Prasanna
  • 1,470
  • 16
  • 30

2 Answers2

21

General technique

Your replacement string can contain arbitrary lisp code. From the documentation for replace-regexp:

In interactive calls, the replacement text may contain ‘\,’ followed by a Lisp expression used as part of the replacement text. Inside of that expression, ‘\&’ is a string denoting the whole match, ‘\N’ a partial match, ‘#&’ and ‘#N’ the respective numeric values from ‘string-to-number’, and ‘#’ itself for ‘replace-count’, the number of replacements occurred so far, starting from zero.

We can use this technique in a number of ways.

Starting from 1

Wat we want to do is replace nn with one more than the replace-count you used with \#.

Call #'replace-regexp with the argument \,(1+ \#):

C-M-% nn \,(1+ \#) will replace nn with 1 first, then 2, 3, etc.

Starting at 25

You can modify this by not just adding one, but (in your example) 25:

C-M-% nn \,(+ 25 \#)

Leading zeros

Or we can use format to add leading zeros. This will replace nn with 000, 001, 002, etc. You can combine other lisp code above to start at 001, 025, or whatever you want.

C-M-% nn \,(format "$03d" \#)

zck
  • 8,984
  • 2
  • 31
  • 65
5

You can also use cua-mode.

Select the rectangle région (all the nn) and then M-x cua-rectangle-mark-mode.

Next, M-n and accept the default values.

zck
  • 8,984
  • 2
  • 31
  • 65
djangoliv
  • 3,169
  • 16
  • 31