How do I do a block search-and-replace with Vim?

I have text in Vim

  1. hit Ctrl+V to put VIm in block mode
  2. highlight the text I want
  3. type : this gives the this prompt :'<,'>
  4. I add to the prompt my regex s/ /*/g. This leaves me with :'<,'>s/ /*/g and the text highlighted
  5. I hit enter

Unfortunately, it operates on the whole line for the block, not just the block. Is there anyway to do a block search and replace?


Solution 1:

When using ex commands in visual block mode, :, they always operate on the whole line. There are two ways around this:

  1. The \%V atom will match only inside the visual area. Try

    :'<,'>s/\%V /*/g
    

    See :help %V

  2. There are special visual versions of some commands, live v_s or v_r. See :help visual-operators