reddit / emacs

Replacing ever instance of a string with increasing numbers

dm_g · 2022-05-27 23:15
I have a text file with certain string. I want to replace it with incremental numbers. For instance, say I want to replace "abc". The first instance should be replaced with "x1", the second with "x2", the third with "x3", etc. For example: "This abc should be replaced with another abc every time an abc is present" should become "This x1 should be replaced with another x2 every time an x3 is present" Is there any package/function that would do this?
aulizko · 2022-05-27 23:35
I know how to replace search hits with increasing number using starting from 0. Like: `M-x query-replace-regexp`, then `abc`, then `x\#`. Then `!`. As for how to start index from 1... I think, elisp forms should do the trick, this link should help: https://masteringemacs.org/article/evaluating-lisp-forms-regular-expressions Something like this: `M-x query-replace-regexp`, then `abc`, then `\,(concat "x" (number-to-string (+ 1 \#)))`. Then `!`.
Gallipo · 2022-05-27 23:43
Yes there are keyboard-macros. Try something like: C-u 1 <F3> C-s a b c <enter> M-b M-d x <F3> <F4> now every subsequent press of <F4> will replace another "abc" with a counter. press C-u 0 <F4> to replace every occurrence of "abc" in the buffer
Alan_Shutko · 2022-05-28 00:00
Cool, I didn't realize kmacro had a counter. I'm used to using registers (C-x r +).
Gallipo · 2022-05-28 00:06
Cool. I didn't know about C-x r +
Gallipo · 2022-05-28 00:09
That's a nice solution. I searched the manual for a counter in `query-replace`, but that doesn't seem to have the counter ability. Does anybody have an explanation for this difference?
FrozenOnPluto · 2022-05-28 00:34
Query-replace-regexp aplies regexp and theres a sneaky expanded language for regexp in emacs, allowing it to call an elisp function that you can write. Ie the above .. thats the difference His solution seems pretty awesome, and if you need to do this a lot, you could script it or bind it to a key or something.
helm05 · 2022-05-28 05:18
You can do the same with iedit package: 1) start iedit on abc 2) replace abc with x\\# 3) hit M-N (use C-u if you want to modify the format spec or start from another number)
myme · 2022-05-28 16:06
If you are using the multiple-cursors package, there's also `mc/insert-numbers`. E.g. to insert increasing numbers at all active cursors starting from 1, press `C-u 1 M-x mc/insert-numbers RET`. ``` mc/insert-numbers is an autoloaded interactive Lisp function in ‘mc-separate-operations.el’. (mc/insert-numbers ARG) Insert increasing numbers for each cursor, starting at ‘mc/insert-numbers-default’ or ARG. ```
dm_g · 2022-06-22 06:00
Thank you very much. This does exactly what I needed. It is also quite useful to know that an e-lisp expression can be used in the replacement. It is magic!