Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace within selection in `vi`

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

like image 597
Agnel Kurian Avatar asked Apr 21 '09 15:04

Agnel Kurian


People also ask

How do I select and replace in vi?

Press y to replace the match or l to replace the match and quit. Press n to skip the match and q or Esc to quit substitution. The a option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y , and to scroll up, use CTRL+E .

How do you replace a word with another word in Vim?

Bookmark this question. Show activity on this post. I can do :%s/<search_string>/<replace_string>/g for replacing a string across a file, or :s/<search_string>/<replace_string>/ to replace in current line.

How do I change a block of text in Vim?

One may overwrite a visual-block of text with another visual-block of text by: Select the first block: ctrl-v move "ay. Select the second block: ctrl-v move c ctrl-o "aP <Esc>

How do I replace a word in vi editor globally?

The % is a shortcut that tells vi to search all lines of the file for search_string and change it to replacement_string . The global ( g ) flag at the end of the command tells vi to continue searching for other occurrences of search_string . To confirm each replacement, add the confirm ( c ) flag after the global flag.


2 Answers

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)

like image 154
Chad Birch Avatar answered Sep 20 '22 15:09

Chad Birch


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.

like image 23
Brad Parks Avatar answered Sep 21 '22 15:09

Brad Parks