11

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?

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

3 Answers 3

17

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.

5
  • Can you please explain about gn motion? I am quite new to vim.
    – WitVault
    Commented Jun 17, 2016 at 6:25
  • 4
    Always ask Vim first: :help gn.
    – romainl
    Commented Jun 17, 2016 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
    Commented Jun 17, 2016 at 19:01
  • @WitVault Instead of typing the word you are going to replace, you can just use search with # and *. With :set hlsearch you will see what is highlighted and then do usual cgn thing.
    – outoftime
    Commented May 21, 2021 at 5:56
  • 1
    @SibiCoder you can use t or f motion to replace prefix you want and n. to move to the next occurance
    – outoftime
    Commented May 21, 2021 at 5:59
7

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.

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

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 and acknowledge you have read our privacy policy.

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