I've been following how to do search replace in vim, but somehow it doesnt work for my case. For example, I have the following code:

x(i,1,1) = y(i,1,1) + z(i,1,1)

Now, I want to change the last index, i.e change "x(i,1,1) to x(i,1,2)" and similar for y and z. I can just go change this manually but if I want to try our vim, just in case I have a larger expressions.

What I did: select the line visual mode (Shift + V). Then press :, then vim has this in the status bar :'<,'>, now I type: s/,1)/,2).

That only changes the first variable. In other words, I have this:

x(i,1,2) = y(i,1,1) + z(i,1,1)

Y and Z are not changed, even if they are on the same line and are selected together with X in visual mode.

Please help

1 Answer 1


So you want to make the substitution occur on every match of the pattern on the line and not only the first match. What you can do is read :h :s, where you'll find:

:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
    See |:s_flags| for [flags].

So you can go to :h :s_flags where you'll find:

[g] Replace all occurrences in the line.  Without this argument,
    replacement occurs only for the first occurrence in each line. 

So you'll add /g to your command like this: :s/,1)/,2)/g and you'll have the behavior you want.

Note that the tag c is often useful when you use g:

[c] Confirm each substitution. 

Also when you use :s by default it operates on the current line so you don't need to visually select the line.

One last note: the UI component where you type :'<,'>s... is not the status line, it's the command line. The status line is the line at the bottom of a window is you set laststatus (see :h status-line and :h Command-line to get the difference)

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.