How do I do a Find and Replace within a selection 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 .
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.
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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With