I'm trying to figure out how to do a search and replace on a visual block selection that will replace all occurrences in the visual block selection without replacing all occurrences on the line.

What I was trying to do was remove all of the whitespace from part of multiple lines.

I had something along the lines of:

<div class="class1 class2">  word            </div>
<div class="class1 class2">  longWord        </div>
<div class="class1 class2">  evenLongerWord  </div>

and I wanted to turn it in to:

<div class="class1 class2">word</div>
<div class="class1 class2">longWord</div>
<div class="class1 class2">evenLongerWord</div>

so I made this selection with visual block mode (i'm representing the selection with | |):

<div class="class1 class2">|  word            |</div>
<div class="class1 class2">|  longWord        |</div>
<div class="class1 class2">|  evenLongerWord  |</div>

and I ran

:'<,'>s/ //g

but that replaced all spaces in the entire line (I'm guessing the 'g' overrides the visual selection column range?) and I ended up with:


but if I run:

:'<,'>s/ //

then it only replaces the first space on each line.

Is this the default behavior for search and replace in visual selection? I'm using someone elses vimrc that I got from this repo amix/vimrc ultimate vimrc so it's possible there is something in there that is causing the search and replace to act differently then it is supposed to.

If this is the default behavior then what would be the best way to do what I was trying to do?

  • 5
    use :'<,'>s/\%V //g... see :h \%V...
    – Sundeep
    Commented Aug 7, 2017 at 15:53
  • 2
    Possible duplicate of vim: how to replace text in visual mode selection?
    – Sundeep
    Commented Aug 7, 2017 at 15:55
  • \%V is exactly what I was looking for, thanks! I feel like the other post is a different question even though it has the same answer. When I went searching for an answer I was searching for 'visual block' specifically so that question didn't show up as a top result.
    – Kevin Aud
    Commented Aug 7, 2017 at 18:03
  • 1
    @KevinAud Visual Block does not have any special status in VIM, it's just a case of Visual Mode as opposed to Insert Mode and Normal Mode.
    – Meitham
    Commented Aug 7, 2017 at 19:13

1 Answer 1


You can specify that the search should only match inside visual selections with the \%V atom, see :help \%V. Thus, you can do:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.