Vim Recipes Searching Searching Over Multiple Files

Searching Over Multiple Files

Problem

You want to search for a particular term in a collection of files. For example, you want to find the files in your project that mention Mr J. Random.

Solution

Use the :vimgrep command: :vimgrep /pattern/ [flags] file0 file1 fileN.

Discussion

In its simplest form, vimgrep takes a word to search for, and a list of files in which to do so. So, to search for grapes in shopping-list.txt you'd run :vimgrep /grapes/ shopping-list.txt.

You can name as many files as you like, but you'll probably want to use shell globbing, see the sidebar for details, instead to specify groups of files. Searching for grapes in all *.txt files could be accomplished with: :vimgrep /grapes/ *.txt.

Globbing

A number of Vim commands support filename globbing. This is a way of selecting a group of files by specifying a pattern matching their names. For example, *.txt refers to all files in the current directory whose names end in .txt. The * is a wildcard and means anything.

** recursively matches directories below the current one, so **/*.txt searches recursively downwards from the current directory for filenames ending in .txt.

If your operating system supports additional globbing patterns, you can use these as well.

You're not restricted to searching on simple words, however. You can use any of Vim's regular expressions between the forward slashes. Searching /tmp/bar.txt and ~/foo.tex for lines starting with numbers: :vimgrep /^[0-9]/ /tmp/bar.txt ~/foo.tex.

vimgrep jumps to the first match it finds. To jump to the next match use :cn; use :cN for the previous.

If you use :grep instead of :vimgrep an external grep-like utility is used to perform the search. The program used is the value of &grepprg. A good choice is Andy Lester's ack which can be used with set grepprg=ack and set grepformat=%f:%l:%m.

The j flag inhibits the jumpiness (Ritalin for Vim); simply saving the search results to the quickfix list (see sidebar for details) and leaving your cursor where it was.

The g flag controls how lines matching the pattern multiple times are handled. If not present (by default), only the first match of a line is shown; otherwise, every occurrence of the pattern is regarded as a separate match.

The flags can be combined in either order.

Quick Fix List

The quick fix list mentioned above is a Vim concept for creating a temporary index of positions in a file. vimgrep stores its results (a file name, a position within that file, and the matched text) in the quick fix list.

To view the quick fix list (i.e. the results of the last search) use :cl[ist]. The results are numbered, so you can jump to a specific one with :cc number.

For more information see :help quickfix.