Vim: open files of the matches on the lines given by Grep?

前端 未结 8 1312
无人共我
无人共我 2021-02-02 16:46

I want to get automatically to the positions of the results in Vim after grepping, on command line. Is there such feature?

Files to open in Vim on the lines give

相关标签:
8条回答
  • 2021-02-02 17:34

    You probably want to make functions for these. :)

    Sequential vim calls (console)

    grep -rn "implements" app | # Or any (with "-n") you like
      awk '{
        split($0,a,":"); # split on ":"
        print "</dev/tty vim", a[1], "+" a[2] # results in lines with "</dev/tty vim <foundfile> +<linenumber>
      }' |
      parallel --halt-on-error 1 -j1 --tty bash -ec # halt on error and "-e" important to make it possible to quit in the middle
    

    Use :cq from vim to stop editing.

    Concurrent opening in tabs (gvim)

    Start the server:

    gvim --servername GVIM
    

    Open the tabs:

    grep -rn "implements" app | # again, any grep you like (with "-n")
      awk "{ # double quotes because of $PWD
        split(\$0,a,\":\"); # split on ":"
        print \":tabedit $PWD/\" a[1] \"<CR>\" a[2] \"G\" # Vim commands. Open file, then jump to line
      }" | 
      parallel gvim --servername GVIM --remote-send # of course the servername needs to match
    
    0 讨论(0)
  • 2021-02-02 17:38

    If you pipe the output from grep into vim

    % grep -n checkWordInFile * | vim -
    

    you can put the cursor on the filename and hit gF to jump to the line in that file that's referenced by that line of grep output. ^WF will open it in a new window.

    From within vim you can do the same thing with

    :tabedit
    :r !grep -n checkWordInFile *
    

    which is equivalent to but less convenient than

    :lgrep checkWordInFile *
    :lopen
    

    which brings up the superfantastic quickfix window so you can conveniently browse through search results.

    You can alternatively get slower but in-some-ways-more-flexible results by using vim's native grep:

    :lvimgrep checkWordInFile *
    :lopen
    

    This one uses vim REs and paths (eg allowing **). It can take 2-4 times longer to run (maybe more), but you get to use fancy \(\)\@<=s and birds of a feather.

    0 讨论(0)
提交回复
热议问题