Skip to Content

Vim - Search and Replace

Posted on

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 use n or N
  • 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.

Or you can use ag or rp

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.

  1. :arg *.html => Add all html files into arglist.
  2. :arg *rb => Add all rb files into arglist.
  3. :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:

  1. :grep pattern **/*html
  2. :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.


comments powered by Disqus