Read more

How to cycle through grep results with vim

Michael Leimstädtner
August 04, 2020Software engineer at makandra GmbH

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.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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

Posted by Michael Leimstädtner to makandra dev (2020-08-04 15:53)