3

Suppose I have a string as follows:

RESULT=100

How would I replace everything following 'RESULT=' so that the string reads:

RESULT=200

The closest I've gotten so far is to use:

:%s/\(RESULT=.*\)\@<=/200/g

But this simply places the desired string after the existing one:

RESULT=100200

Can anyone help me?

Kindest regards!

3

One way to do this is by using \zs to set the "start" of the match, so that everything before \zs is untouched by the replacement:

:%s/RESULT=\zs.*/200/g

Your original attempt using a lookbehind was also on the right track: you just put the .* part in the wrong place:

:%s/\(RESULT=\)\@<=.*/200/g

This replaces anything that comes after a RESULT=, whereas your search replaced nothing that comes after a RESULT=.*.

However, \zs and \ze are recommended over lookarounds when it's possible to use them, because lookarounds can be slow.

As @DJMcMayhem notes in the comments, yet another approach is to allow the substitution command to replace the RESULT= part, but include that text in the replacement by using a capture group:

:%s/\(RESULT=\).*/\1200
  • 1
    Perfect solution - it says I can't upvote yet, so I will wait 11 minutes and set as the correct answer. Thank you! – Jack Rolph Sep 25 at 8:24
  • 1
    @JackRolph Glad to help. See my edit for a bit more explanation. – Rich Sep 25 at 8:58
  • 1
    One other way you could do it is to use two capture groups: :%s/\v(RESULT\=)(.*)/\1200 – DJMcMayhem Sep 25 at 15:30
  • @DJMcMayhem Good point! But in fact a single group will suffice: %s/\v(RESULT\=).*/\1200 – Rich Sep 25 at 16:37
2

@Rich's solution is a perfect general solution, however maybe your question is a good example of an XY problem. For your specific use case Vim has :h CTRL-A and :h CTRL-X:

CTRL-A          Add [count] to the number or alphabetic character at
            or after the cursor.

CTRL-X          Subtract [count] from the number or alphabetic
            character at or after the cursor.

So in your case you can simply put the cursor anywhere between the beginning of the line and the 1 and in normal mode use 100CTRL+a

  • 2
    You could also do this just on the lines with RESULT= with a :global :nomal command! g/RESULT=/execute "normal! 100\<C-A>" – Rich Sep 25 at 10:17
  • 1
    Thanks very much for this! However, I am changing a text file in a bash script and therefore the vim code is more useful in this instance. Nonetheless, thank you for the answer - this will be useful in many other circumstances! – Jack Rolph Sep 25 at 12:53
  • 1
    @JackRolph you're welcome :) One last piece of advice: if you are writing a bash script which invokes Vim to do this kind of transformation you most probably want to use sed(1) instead :) – statox Sep 25 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.