Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files with grep and open in editor

Tags:

grep

bash

vim

emacs

I'd like to use grep for searching through a directory and open the files with matches in an editor of choice. (emacs or vim will do.)

I can open the first match via vim $(\grep -l "static void main" *), but this won't open the other matching files. The \ in front of grep is used to use an unmodified grep, usually I have colored grep which will not work because it leads to wrong filenames.

I am aware that I can try find, pipe the results each to grep and open then the file found in question each in a new editor, with the help of xargs.


Best working solution:

USAGE:
grepe static void main or
grepv static void main.

No "" needed.

INSTALL:
Put this into your .bashrc.

#emacs:
grepe(){
    emacs $(\grep -irl "$*" .)
}
#vim:
grepv(){
    vim $(\grep -irl "$*" .)
}
like image 272
sjas Avatar asked Dec 27 '13 15:12

sjas


3 Answers

for other editor (like sublimetext subl) I use to do that:

grep ... -l | xargs subl

the -l will only display the path so then you can directly open with your editor if it has command line support

like image 198
Barbz_YHOOL Avatar answered Oct 12 '22 23:10

Barbz_YHOOL


You can use ** in the file pattern to search recursively. For example, to search for all lines containing dostuff() in all .c files in the parent directory and all its subdirectories, use:

:vimgrep /dostuff()/ ../**/*.c

Read more @ http://vim.wikia.com/wiki/Find_in_files_within_Vim

For an editor independent way, try

vim -o $(grep -rl string directory)
like image 43
Fredrik Pihl Avatar answered Oct 13 '22 00:10

Fredrik Pihl


First off, you are not specifying the search path after the pattern.
For the simplest method:

vim $(grep -l "static void main" *)

For the smarter one (doesn't open Vim unless there were any results):

files=$(grep -l "static void main" *) && vim $files
like image 30
krystah Avatar answered Oct 13 '22 00:10

krystah