To simplify the other substitute solutions given, one thing that no one has mentioned so far is that you can use the *
command to search for the word under your cursor. This pulls the word into the "/
register WITH the \<\>
, so you don't have to type it yourself.
Then, when you go to make your substitution, you can leave the search text blank (it will automatically search for what is in the "/
buffer). The process could look like this:
for(int i = 0; i < len; ++i);
/i <return>
*
:s//j/g
This finds i<space>
, searches for \<i\>
, and i with j on the current line, resulting in:
for(int j = 0; j < len; ++j);
You can combine this easily with line-wise visual selection (V
) to select the lines you want to change. You could even v
or ctrl+v
to make a visual selection or visual blocks. With the latter two, if you have a match on the same line, but outside your visual selection, you'll need to use the \%V atom and paste (ctrl-r /
) the /
register in the search command to only substitute within the visual selection. For example:
for(int i = 0; i < len; ++i); i
/i <return>
*
vi(
:s/\%V<ctrl-r>//j/g
The last line becomes:
'<,'>s/\%V\<i\>/j/g
This finds i<space>
, searches for \<i\>
, selects inside the parentheses, and replaces i with j ONLY within the visual selection, resulting in:
for(int j = 0; j < len; ++j); i
But again, that only applies if you have matches on a selected line, but outside a visual selection (like that trailing i).