How to cycle through grep results with vim

Updated . Posted . Visible to the public.

grep is the go-to CLI tool to accomplish tasks like filtering large files for arbitrary keywords. When additional context is needed for search results, you might find yourself adding flags like -B5 -A10 to your query. Now, every search result covers 16 lines of your bash.

There is another way: You can easily pipe your search results to the VIM editor and cycle through them.

Example: Searching for local occurrences of "User"

vim -q <(grep -Hn -r "User" .)

# vim -q starts vim in the "quickfix" mode. See ":help quickfix"
# grep -Hn formats search results with filename and number (required for vim -q)
# grep -r "User" is the actual search query
# vim <(grep) pipes grep results to vim

This command will open vim with the cursor pointed to the file and line number of the first match.
Use :cn and :cp to jump to the next or previous search result. Exit vim with :q.

Bonus

Michael Leimstädtner
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2020-08-04 13:53)