Search code examples
regexvim

Display all lines matching a pattern in vim


I search for a particular string in a file in vim, and I want all the lines with matching string to be displayed, perhaps in another vim window.

Currently I do this:

Search for 'string'

/string

and move to next matching string

n or N

Bur, I want all the lines with matching string at one place.

For example:

1 Here is a string

2 Nothing here

3 Here is the same string

I want lines 1 and 3 to be displayed as below, highlighting string

1 Here is a string

3 Here is the same string


Solution

  • :g/pattern/#<CR>
    

    lists all the lines matching pattern. You can then do :23<CR> to jump to line 23.

    :ilist pattern<CR>
    

    is an alternative that filters out comments and works across includes.

    The command below:

    :vimgrep pattern %|cwindow<CR>
    

    will use Vim's built-in grep-like functionality to search for pattern in the current file (%) and display the results in the quickfix window.

    :grep pattern %|cwindow<CR>
    

    does the same but uses an external program. Note that :grep and :vimgrep work with files, not buffers.

    Reference:

    :help :g
    :help include-search
    :help :vimgrep
    :help :grep
    :help :cwindow
    

    FWIW, my plugin vim-qlist combines the features of :ilist and the quickfix window.