views:

1141

answers:

5

How do I do a Find and Replace within a selection in vi?

+3  A: 

Some more help here Search and replace in a visual selection

Lazarus
+6  A: 

If you used Visual Mode to select, then:

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

VIM will place the range ('<,'>) automatically if you go into Command Line Mode (by pressing ':') from within Visual Mode.

Tomalak
+9  A: 

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)

Chad Birch
Caveat: the range only works linewise! If your selection contains only part of a line the search and replace will work on the whole line. Getting partial line find and replace requires scripting afaik.
A: 

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

:%s/foo/bar/g

Omit the g to do a local replace.

lfaraone
The local is local to the current line
Lazarus
A: 

The above solutions 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. If you have more than one line selected, this will work over multiple lines too.

Brad Parks