help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Emacs regexp/incrementer question


From: Friedrich Dominicus
Subject: Re: Emacs regexp/incrementer question
Date: 16 Jan 2003 13:17:20 +0100
User-agent: Gnus/5.0808 (Gnus v5.8.8) XEmacs/21.4 (Native Windows TTY Support)

"Tim Morley \(remove vegetable for email address\)" <tim@teamlog.turnip.com> 
writes:

> Hi all.
> 
> Does anybody know of a way to include an incrementing number in a regexp
> search-and-replace in Emacs? What I want to do is search for a regexp, and
> the first time I find it, replace it with "case 1", the second time replace
> it with "case 2", etc.
> 
> Even if the solution is a several-stager, I'd be more than happy, because
> I'm currently having to replace each occurrence with "case xxx" and then
> change each "xxx" to a number by hand afterwards -- hardly ideal. I could
> use awk or something to change the xxx's to incrementing numbers, but I'd
> much prefer to do it all in Emacs if I can.
> 
> Thanks in advance for your help.
Here's a starting point for doing that
(defun replace-with-changing-replacement (pattern replacement)
  (interactive "sPattern: \nsReplacement: ")
  (let ((count 1))
    (while (re-search-forward pattern nil t)
      (let ((repl (format "%s %d" replacement count)))
        (incf count)
        (replace-match repl)))))

Not really tested but just checked it works for this
foobar 
another foo
yet another foo
and last but not foo least foo
foo foo foo 
end foo
M-x replace-with-changing-replacement RET
Pattern: \<foo\> RET
Replacement: case RET

will change that too:
foobar 
another case 1
yet another case 2
and last but not case 3 least case 4
case 5 case 6 case 7 
end case 8

Which is what you want.

Regards
Friedrich




reply via email to

[Prev in Thread] Current Thread [Next in Thread]