36

When using the grep plugin to VIM, I can search the current directory for all occurrences of a string within a set of files, like this:

:grep Ryan *.txt

This outputs something like this:

file1.txt:3:Ryan was here
file2.txt:10:Ryan likes VIM
file3.txt:5:superuser.com is a fav of Ryan
(1 of 3): Ryan was here
Press ENTER or type command to continue

If I press enter, it just takes me back to my editor. What I really want to do is be able to open up one of those files and jump to the place where the string was found. Is there a way to do this? The 1 of 3 part makes me think there's a way to tab through the results, but I don't know what commands are available to me. Can anybody shed some light on this?

1 Answer 1

38

When you press ENTER, you should be looking at line 3 of file1.txt. To jump to the next match, execute :cn; to jump to the previous match, execute :cp. Executing :copen will open a window containing the list of matches. Move the cursor to the desired match and press ENTER to jump to that match.

For more on using :grep, see

:help grep
:help quickfix.txt

Typing :cn and :cp to move forward and backward in the quickfix list can be awkward, so I use these mappings:

nmap <silent> <C-N> :cn<CR>zv
nmap <silent> <C-P> :cp<CR>zv

Also, the :grep command is not a plugin; it's part of Vim.

2
  • Great answer, thanks! BTW, can you do a recursive search through folders with vim grep?
    – Marplesoft
    Feb 22, 2011 at 16:42
  • As long as you are running on a Unix system, you can add whatever arguments to Vim's :grep that you would add to a grep command executed from the shell. So, you could do a recursive search through all .txt files in and below the current directory with :grep -R --include=*.txt Ryan .. You can also perform a recursive search using Vim's :vimgrep command, but the arguments are different and I seldom use because it is slower than :grep.
    – garyjohn
    Feb 22, 2011 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.