Hind Forsum
Hind Forsum

Reputation: 10507

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?

Upvotes: 5

Views: 11768

Answers (2)

krzemian
krzemian

Reputation: 388

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

Upvotes: 17

romainl
romainl

Reputation: 196546

You can use \%V to restrict the search to the visual selection:

:'<,'>s/\%Vs/k/g

See :help \%V

Upvotes: 11

Related Questions