7

I know there is one way to search and replace variable occurrences across a source file.

But is there any better way by which if I rename a variable at one place it gets renamed at other places as well without search and replace or substitute?

  • The answer will depend on the language. In some codebases, it may be practical to write a regex that precisely matches your situtation. – acbabis Jun 17 '16 at 17:22
12

You can just use the usual workflow search and replace:

/original
cwreplaced
n.n.

You can take also advantage of the gn motion:

/original<CR>
cgnreplaced<ESC>
.....

cgn will change the next matched pattern, so instead of using n.n. to go to next and repeat you can just .. which means replace next.

gn means "search for next occurence and start a visual selection over it", you can read more about it on the doc: :h gn.

  • Can you please explain about gn motion? I am quite new to vim. – WitVault Jun 17 '16 at 6:25
  • 3
    Always ask Vim first: :help gn. – romainl Jun 17 '16 at 7:27
  • @nobe4 : You can improve your answer. :) User might want to replace with all $first with $second, not $first_variable. Can we go with \<pattern\>? Or, suggest a better way! – SibiCoder Jun 17 '16 at 19:01
5

You can use a substitute:

:%s/original/replaced/g

Will substitute across the entire file (%) original by replaced. And will replace multiple occurrences on the same line g.

If you are not confident about automatically replacing, you can add the c flag to ask for confirmation each time.

  • I do not want to blindly to search and replace. – WitVault Jun 17 '16 at 6:24
  • 3
    Then the c flag is the way to go. – nobe4 Jun 17 '16 at 6:26
2

I'd like to add another option.

You can do /original and then do :%s//replacement. (Use /c at the end if you want confirmation).

Although you are pressing 3 more keys, this has an advantage over doing just %s/original/replacement because it provides a visual cue that your search is correct.

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.