Grep for String and open at the corresponding line

为君一笑 提交于 2020-01-11 10:03:13

问题


I'm having several occurrences of a specific string over several files in several lines obtained with grep.

$ grep -rn --include="*.cpp" mystring
lib/mlib/actionbuttonrule.cpp:300:  mystring Foobar...
lib/mlib/actionbuttonrule.cpp:314:  other mystring
lib/mlib/item.cpp:3025:             /* mystring**/
lib/mlib/item.cpp:3082:             mystring Foobar...
lib/mlib/item.cpp:3095:             Foo mystring bar

I'd like to open these files sequencially on the corresponding lines. I tried to do it with vim, but so far no success when it comes to open the line. Mustn't be vim or grep, but I'd assume there must be some kind of functionality out there...


回答1:


You can load your grep output in Vim's quickfix list with:

$ vim -q <(grep -rn --include="*.cpp" mystring)

Go to the next occurence with :cn and to the previous occurrence with :cp.

See :help -q and :help quickfix.




回答2:


Here is another way to do

$ grep -rn --include="*.cpp" mystring > op
$ vim op

Then use gF and to come back to file op, use Ctrl + 6




回答3:


A trick to use vim as a pager is to pass it a hyphen character. This causes it to read from STDIN instead of from file

grep -rn --include="*.cpp" mystring | vim -


来源:https://stackoverflow.com/questions/49152029/grep-for-string-and-open-at-the-corresponding-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!