When I visually select text and enter : I'll get this:


Now I can enter a substitution to be done on those lines. However, what if I wanted to do several substitution, e.g. foo to bar and hello to world? What would I need to do then?

  • 3
    Fun fact!: :* is the same as '<,'>. e.g. :%s/foo/bar/ -> :*s/foo/bar/ – Peter Rincker Jul 14 '16 at 20:50
  • My example should be: :'<,'>s/foo/bar/ -> :*s/foo/bar/ – Peter Rincker Jul 14 '16 at 22:04
  • @PeterRincker I would actually consider this the best answer, because it's the least interruptive – hgiesel Jul 17 '16 at 10:31

Using gv is a good option. Another alternative is to just hit : Up after you do your first substitution. This will bring up your previous substitution with the :'<,'> text at the beginning.

Then, you can edit the previous command with your cursor keys and backspace.

This works because conveniently, the :'<,'> causes the substitution to be limited to your current or previous visual selection if you don't have text visually selected at the moment.


Assuming your exact example case you can use :Subvert from Tim Pope's abolish.vim.


You can see this in action in the the Vimcasts episode: Supercharged substitution with :Subvert

  • 1
    +1 for Tim Pope's abolish. – Sato Katsura Jul 15 '16 at 9:37

While there are probably ways to do it all in a single substitution, I think that probably the most practical way of doing it is simply:

  1. Do the first substitution
  2. Press g then v (this will select the previous visual selection)
  3. Do the second substitution

See :h gv for more info.


Define a dictionary containing your substitutions: let g:dict={'foo': 'bar', 'hello': 'world'} Then you can substitute several items at once: '<,'>s/foo\|hello/\=get(dict, submatch(0))/g or even completly dynamic: exe "'<,'>s/". join(keys(dict), '\|'). '/\=get(dict,submatch(0))/g'

This works also, if you want to replace at the same time foo by bar and bar by foo.

  • This seems to complicated to me to do during edit time. I'd much rather '<,'>!sed 'do substitutions' – hgiesel Jul 14 '16 at 23:00
  • @hgiesel you can do that, but note, that multiline substitution is a lot trickier and also you can't use special RE features. – Christian Brabandt Jul 15 '16 at 7:40

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.