Vim - Search and Replace
Notes: All below commands work with Vim current working directory. Use
:pwd
to show current dir or use :cd mydir
to change.
Searching in current file
- Just search:
/
, and usen
orN
- Search backward:
?
- Search again using previous search pattern:
//
- Searching the word under the cursor
*
, search backward:#
Search in multiples files
1. vimgrep
Searching with vimgrep
will populate the quickfix list with the result of search.
- Search in project:
:vimgrep pattern **/*.rb
and use:copen
to open result list. - Use
:cnext
or:cprev
to go through the results.
2. grep
Using :grep
and :vimgrep
is similar. But grep
is faster.
Find and Replace
In a file
- Replace in a line:
:s/pattern/replace/g
. - Replace in a file:
:%s/pattern/replace/g
.
Multiple files
Vim has list named arglist. If
you want to find and replace multiple files, you need to add those files into
arglist
and do operators on this list.
:arg *.html
=> Add allhtml
files into arglist.:arg *rb
=> Add allrb
files into arglist.:argdo %s/pattern/replace/ge | update
=> Replace in all files in arglist.
We can do the same with vimgrep
and grep
. Just use :cdo
instead of
:argdo
:
:grep pattern **/*html
:cdo s/blink/div/g | update
Use Plugins
- fzf and fzf-vim for search files, buffers, hsitory, tags, …. And we can add those files to
quickfix
list, use:cdo
to replace & update like above. Read more fzf.vim#185 - Use ripgrep instead of
grep
.fzf
and:Rg
is great combo. Or use can use ag instead.