Friday, May 25, 2012

Use grep to search a string in files recursively and store the grep results in a quickfix window

Use grep to search a string in files recursively and store the grep results in a quickfix window
:grep -r 'pattern' . --include '*.c'

:copen             " open the quickfix window
:cw                " open the quickfix window if there are entries (so if your grep has no results, it won't appear).

<ENTER>            " Open the line of a file in a new buffer.
Ctrl-W <ENTER>     " Open the file/line in a new window.
:.cc               " Open the line of a file in a new buffer.

:cfile debug.txt   " read the content in debug.txt to a quickfix window.
                   " Note: follow this format: "filename:line number:error message"

:cgetfile debug.txt " Just like "cfile" but don't jump to the first entry.

:cclose            " close the quickfix window.
:quit              " close the quickfix window.

Edit ~/.vimrc:
" Find String Search String.
" Open quickfix window automatically after running grep command.
command! -nargs=+ Mygrep execute "silent grep! <args>" | copen

:Mygrep -r 'pattern' . --include '*.c'

Performing a customized grep search on the word under the cursor:
map <F4> :execute " grep -srnw --binary-files=without-match --exclude-dir=.git --exclude-from=exclude.list . -e " . expand("<cword>") . " " <bar> cwindow<CR>

:help grep
:help copen
:help quickfix

Reference
http://stackoverflow.com/questions/1234394/selecting-resulting-files-from-grep-in-vim
http://stackoverflow.com/questions/6373293/vim-how-to-store-the-grep-results-in-a-buffer
http://vim.wikia.com/wiki/Find_in_files_within_Vim

No comments: