Running spacemacs 0.200.13 on emacs 25.2.2 on Kubuntu 18.04.
I need to search and replace only on lines containing a specific string.
Interactively, I use occur
, move to the occur
buffer, and do all search and replacement there.
I would, now, like to do the same in Elisp code. So, I wrote the following code:
(defun xx-things ()
(interactive)
(save-excursion
(goto-char (point-min))
(while (search-forward "A" nil t)
(while (search-forward "B" nil t)
(replace-match "C" 1)))))
And used it on a buffer with:
AB
BB
CB
But it replaces all Bs with Cs whereas it should only replace AB with AC.
What is wrong here? How do I set it right?
B
you must set theBOUND
argument ofsearch-forward
to(line-end-position)
. Depending on what you want you also could also add(forward-line 0)
after(search-forward "A" nil t)
to start the search forB
at the beginning of the line containingA
. Post an answer when you have a working version and accept it.bound
orlimit
for mysearch-forward
. I tried(while (search-forward "A" (line-end-position nil) nil t)
but that does not work. Tried googling for setting the limit/ bound, but no luck. What am I doing wrong?(line-end-position)
but replace thenil
with(line-end-position)
. Currently your argument list looks like:STRING="A", BOUND=(line-end-position nil), NOERROR=nil, COUNT=t
. Two problems:NOERROR
should bet
andCOUNT
must benil
or a number, it must not bet
.