Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I search my directory tree for contents within a file for a git managed project?

I like the unix find command but I always find it too 'fiddly' to use when I want to search through my project looking for a piece of text in any file in any directory or subdirectory.
Is there an easier way to do this?

like image 810
Michael Durrant Avatar asked Aug 09 '12 16:08

Michael Durrant


4 Answers

Try grep utility:

  1. For searching a string in the directory tree recursively :

use: grep -rl alvin .

  1. Search multiple subdirectories:

Your recursive grep searches don't have to be limited to just the current directory. This next example shows how to recursively search two unrelated directories for the case-insensitive string "alvin":

grep -ril alvin /home/cato /htdocs/zenf
  1. Using egrep recursively:

You can also perform recursive searches with the egrep command, which lets you search for multiple patterns at one time.

egrep -ril 'aja|alvin' .

Note that in this case, quotes are required around the search pattern.

Summary: grep -r notes:

A few notes about the grep -r command:

  • This grep command doesn't make much sense unless you use it with the -l (lowercase "L") flag as well. This flag tells grep to print the matching filenames.

  • Don't forget to list one or more directories at the end of your grep command. If you forget to add any directories, grep will attempt to read from standard input (as usual).

  • As shown, you can use other normal grep flags as well, including -i to ignore case, -v to reverse the meaning of the search, etc.

like image 189
Prabhat Kumar Singh Avatar answered Nov 04 '22 03:11

Prabhat Kumar Singh


git grep is one way to do this, but it'll ignore untracked files (so it's not exactly equivalent to whatever you're doing with find). A few other ways to get at this that avoid find's curious syntax:

grep -r "<string>" /path/to/repo

You might also try my personal favorite grep alternative, ack, which outperforms both grep and git grep in my anecdotal experience:

ack "<string>" /path/to/repo ;# path is unnecessary if you're already in the repo
like image 45
Christopher Avatar answered Nov 04 '22 05:11

Christopher


Grep is simplest approach.

grep -r 'text to find' .
like image 27
Bohdan Avatar answered Nov 04 '22 04:11

Bohdan


git grep "your text string", from the applcation's base directory is a great way to do this.

Also as Christopher points out ack is useful.

His install method didn't work for me. I had to do:

sudo apt-get install ack-grep

and then for convenience

alias ack='ack-grep '  # So that I can just type ack "string"

which I'll also add to my ~/.bash_aliases file.

like image 32
Michael Durrant Avatar answered Nov 04 '22 03:11

Michael Durrant