Search code examples
vimreplaceselectionmode

vim: how to replace text in visual mode selection?


I've got a text file:

hello world ssh! 
this is your destiny 
Oh my goodness 

In visual mode, I select from "world" to "my": I wish to change letter 's' into 'k' in my selection.

I definition cannot use line-mode because in that way the 3rd line's "goodness" will be changed.

So how to do this replacement in visual mode?


Solution

  • To achieve the same in normal mode (after you've made a selection and escaped from it), use the \%V atom along with the % range modifier together in a substitute query

    :%s/\%Vs/k/g
    

    :s/foo/bar - a substitute query
    % - makes sure it applies to all lines in the file
    \%V - limits the range to the last visual mode selection (i.e. the one you get with gv)
    g - a global flag which makes sure all occurrences will be affected (instea of the first one in each line, which is the default behavior)

    More at http://vim.wikia.com/wiki/Search_and_replace_in_a_visual_selection