Search and Replace in Vim

Often people ask how It is possible to live with an editor like Vim, that does not allow multi-line-editing and that has even trouble with search and replace. Here is my answer – As with most tools or languages (CMake, bash, …  whatever you hate – maybe except for PHP) everything sucks much less if you take the time to figure out how it works.

" TASK - Replace 'foo' with 'bar'
" % - in whole buffer
" g - all occurrences in line - not only the fist 

:%s/foo/bar/g


" TASK - Replace word under the cursor with 'bar'
" <C-r><C-w> - insert word under cursor
:%s/<C-r><C-w>/bar/g

" viwy - yank inner word
" <C-r>" - paste yanked word
viwy:%s/<C-r>"/bar/g

" * - selects word under cursor and searches for next occurrence
" // - repeats last search
hit *  on word, and :%s//bar/g

" replace the last searched text with the last yanked text
:%s//\=@"/g

 

Leave a Reply

Your email address will not be published. Required fields are marked *