2

I am trying to figure out a way to replace a string in a text file by a number that increments by more than 1. I am trying to turn a couple of lines like this:

result_A_in_S1-S2.txt
result_A_in_S1-S2.txt
result_A_in_S1-S2.txt
result_A_in_S1-S2.txt

Into something that scales up sequentially for S1 and S2.

result_A_in_1000-1003.txt
result_A_in_1004-1007.txt
result_A_in_1008-1011.txt
result_A_in_1012-1015.txt

I want to know if I can define a string with replace regexp and then have that string be replaced with some starting number, and as it finds the next occurrence of string, it replaces with starting number + chosen increment.

I am just now starting learn Emacs and am pretty unfamiliar with it.

Toto
  • 89,455
  • 62
  • 89
  • 125
Cgeo629
  • 21
  • 2
  • I'm guessing this might be a duplicate... – Drew Mar 28 '18 at 01:27
  • 1
    That was also my initial thought. I know there are other Q&As about generating sequences generally (which do tend to include answers like mine here, amongst other approaches), but this question had a specific need which seemed best met with a specific answer. – phils Mar 28 '18 at 02:48

1 Answers1

4

Yes, you can do that with [query-]replace-regexp in Emacs, by evaluating elisp in your replacement, and utilising the zero-based replacement counter \#. e.g.:

M-x query-regexp-replace RET S1-S2 RET
\,(let ((start (+ 1000 (* 4 \#)))) (format "%d-%d" start (+ start 3))) RET

phils
  • 71,335
  • 11
  • 153
  • 198
  • Thank you so very much, I found a much dumber brute force work around, but it this is lovely. I have still so much to learn about emacs. – Cgeo629 Mar 27 '18 at 21:08