Find and replace within the selection in `vi`

How can I find and replace within a selection in vi ?

+41
vim editor replace vi
Apr 21 '09 at 15:22
source share
5 answers

Select the text in visual mode (I assume what you are doing), then press : to start typing a command, you will see something like this on the command line:

 :'<,'> 

This means that the team will apply to the selection. Then type s/search/replace/ and press enter. (Add g after the third slash if you want to replace all matches, and c if you want confirmation for each replacement)

+45
Apr 21 '09 at 15:25
source share

Most of the other solutions offered here work on the ENTIRE line, which selects what might not be what you want.

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

 :%s/\%VSEARCH/REPLACE/g 

This will only search and replace in the visually selected section, replacing SEARCH with REPLACE. If you have selected more than one line, this will work on several lines as well.

+65
Jul 09 '09 at 14:09
source share

If you used Visual mode for selection, then:

 :'<,'>s/regex/replacement/options 

VIM will automatically place the range ( '<,'> ) if you go to command line mode (by pressing ':' ) from visual mode.

+12
Apr 21 '09 at 15:25
source share
+6
Apr 21 '09 at 15:23
source share

If you want to perform a global search and replace (with optional regular expressions) for all instances in the file, I would do the following:

 :%s/foo/bar/g 

Lower g to perform a local swap.

-3
Apr 21 '09 at 15:28
source share



All Articles