Greppin’ Baller Style

So you wanna find something in yer code? Yep. Grep.

There comes a time when you really just want to find something, but either the grep is going to take way too long or you just like being efficient down to the microsecond. Either way, I’m about to show you how I grep. /flex

Anytime I grep, this is generally how I roll:
grep -IirFn "What I'm looking for" .
Let’s break it down now! We’re grepping, but what are all those options?

  • -I – ignore binary files (ie: don’t grep through my images, bro)
  • -i – case insensitive. I know I grepped for “What I’m looking for”, but maybe it’s not capitalized
  • -r – recursively grep through this directory and each one inside it… recursively. Ahem. Bad joke.
  • -F – search for my string literally, no regex!
  • -n – prepend each found line with the corresponding line number – such help! =]
  • "What I'm looking for" . – so what I’m looking for and the dot at the end is to tell grep to start looking here (and sneaky tip, include hidden files!)

Ludicrous speed, ENGAGE

Nerd Remix! Betcha Picard wished he said that once in a while. #nerdage

So let’s say this is all well and good, but we gotta keep on rollin’ through a huuuuuge codebase with lots and lots of stuuuuuuff. What then?!

This is generally when I like to FIND the context of the files I can get at and only grep through those:
find . -name "*.php" -type f -exec grep -FnH "DOING_AJAX" {} \;
Wait… that’s different…. and the arguments aren’t the same. What just happened?! D=

All great questions! Thank you for asking, me! =D

  • find . – find is the command, the dot here is for the same reason (start looking here and include hidden files!)
  • -name "*.php" – this tells find to go find files with a .php extension in the name. Keep in mind, if you want to not bother with case sensitivity, you can replace “-name” with “-iname” =]
  • -type f – this tells find to only worry about FILES (as opposed to directories, etc…)
  • -exec blah blah – this is pretty cool. You can tell find to execute any command upon the matched item. So here we told it to execute a grep. Make sure you end your exec with a fully escaped semicolon too!
  • grep -FnH – We know about the -Fn already, but the -H allows our grep to also prepend the matched grep with the filename also. So -nH gives us the filename:linenumber: match.

I hope that helps you get to what you’re looking for just a little quicker =]

Leave a Reply...