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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)