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.

2
  • I'm guessing this might be a duplicate... Commented Mar 28, 2018 at 1: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. Commented Mar 28, 2018 at 2:48

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 it might have saved me some time today if you had explained your brute force workaround :) For my future reference, here's how I appended numbers with a computed value <kbd>M-x</kbd> query-regexp-replace <kbd>RET</kbd> .* <kbd>RET</kbd> \,(format "%s %d" \& (- (string-to-number \&) 616))` <kbd>RET</kbd> ` Can't get formatting to work in comments but I am sure I can figure it out next time
FYI you can use \#& in place of (string-to-number \&) -- and likewise for backreferences \#1, \#2, etc, whenever capturing strings of numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.