Find and Replace within selection in `vi`

Select the text in visual mode (I assume that's what you're doing), then press : to start typing a command, you'll see something like this appear in the command line:

:'<,'>

That means that the command will apply to the selection. Then type s/search/replace/ and hit enter. (Add a g after the third slash if you want to replace all matches, and a c if you want a confirmation for every replace)


Most of the other solutions suggested here work over the ENTIRE line in which the selection occurs, which may not be what you want.

To search and replace ONLY in the selection, first visually select the text, then use a command like so:

:%s/\%VSEARCH/REPLACE/g

This will do the search and replace only in the visually selected section, replacing SEARCH with REPLACE. If you have more than one line selected, this will work over multiple lines too.