Using grep to search in files

November 5, 2008 – 11:14 pm

I’m moving away from eclipse and more and more into the wonderfull (and cold) world of the command line.

So I need to search for file that contain something in the current directory and its subdirectories all the time

grep -R "something I'm searching for" .

Grep is the way. And with some colors it’s still nicer

grep -R --color "something I'm searching for" .

Now what if I only want files that end with .py that’s a little more subtle

grep -R "something" $(find . -name "*.py")

Now if you want still better you can go for ack which is a grep like tool, only better

ack "something" .

Yeah you don’t have to type the -R it’s the default, also the executable is called ack-grep under debian/ubuntu.

Don’t feel like typing the . that says you’re searching in the current directory ? Add that to your .bashrc

g() {
  if [ $# = 1 ]
  then ack -i $1 .
  else ack -i $@
  fi
}

Now you can search in the current directory with a simple

g something

Don’t forget to replace ack by ack-grep under debian/ubuntu.

  1. 2 Responses to “Using grep to search in files”

  2. Even better, you don’t have to specify the . as the path. It just assumes the current directory if you don’t specify.

    Just make sure you don’t get stung by ack skipping a file that you wanted it to search through. It only searches through files that it knows the type of (see ack –help-types)

    By Andy Lester on Nov 6, 2008

  3. Oh you’re right ack does take the current folder as a default ! I didn’t had to define the g function !

    Yeah ack only search for source files by default and not in the .svn .git .hg folders and a few others like build.

    By admin on Nov 6, 2008

Post a Comment