How to store grep results in a buffer in Vim?
You can go to older searches, and back easily:
:copen
:colder " goes to older
:cnewer " newer
You can have another search using lvimgrep
(uses location window):
:lopen
:lnext
etc...
It also has history:
:lolder
:lnewer
You can read into any buffer:
:r!grep bla **/*.cs
Finally, any command that gives output, can be redirected with the redir
command:
:redir >> file
:grep bla **/*.cs
:redir END
See :he redir
for the many ways to use it (redirect into registers or variables).
Over the years of reading all kind of logs, I learned this little trick:
:%!grep pattern
It simply replaces the current buffer contents with grep output (so to go back to the original logs you have to simply press u
).
You can also use it with other tools:
:%!ack pattern
:%!ag pattern
:%!rg pattern
Note that you can also run these commands on other files then the current one. The following 2 commands would replace the current buffer with results of grepping over the current file (second %
character, which would be redundant for grep in this case) and otherfile.txt respectively:
:%!grep pattern %
:%!grep pattern otherfile.txt
For me it's the simplest and the best solution for fast grepping of big files in Vim and I'm pretty surprised no one ever mentioned it.
I thought that :grep
results were stored by default in the quickfix
window.
Try to use :copen
after running a grep command. I expect that you'll find your results there.
( :cclose to close the quickfix window)
It is not really a buffer, but as long as you are not starting another search your result list will stay intact.
You can "yank" the content of the quickfix window to a new buffer.
- Go into quickfix with
:copen
- Yank its content with
yG
- open a new buffer with
:new
- Paste the content with
p
- Save it with
:w Process1.txt
Repeat and rinse for multiple search/process.
@romainl 's answer on how grep results into separate buffer or split window gives a much cleaner answer than quickfix/location lists.
:vnew | 0r!grep foo #
:tabe | 0r!grep foo #
but Quickfix lists are sort of intended for what you are doing but not the way you are doing it; however, it's tedious to set up unless it's a recurrent task.