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 usenorN - 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 **/*.rband use:copento open result list. - Use
:cnextor:cprevto 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 allhtmlfiles into arglist.:arg *rb=> Add allrbfiles 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
quickfixlist, use:cdoto replace & update like above. Read more fzf.vim#185 - Use ripgrep instead of
grep.fzfand:Rgis great combo. Or use can use ag instead.