Monday, March 18, 2013

recursive grep

tl;dr: recursive grep can be done via
grep -RHin TEXT_TO_FIND --include "FILE_PATTERN" . 

One of the nice things about my new work machine being OSX is slipping back into the good old Unix command line.

A fairly common task is the "recursive grep": finding pattern matches in files through a subtree of directories.

My default for that, the one I can type without looking anything up (because it was easy to reconstruct) worked but was kind of crappy:
find . -name "*js" -exec grep -i getUserMedia /dev/null {} \;

That's using the find command and then exec'ing out to grep... {} is the file name passed into the exec'd command, and the /dev/null is there as a bogus second filemame to make sure the name of the actual file is printed by grep. Crappy, especially if directories match the file pattern and you get "Is a directory" errors all over the place.

Modern grep can do the recursive serach for us, as well as the file pattern matching. So a much better formulation is:
 grep -RHin getUserMedia --include "*js" .
The R means recursive, H prints the filename and then n even prints the line # in the file.

(For both the crappy and the modern example, the "." tells the process to start in the current directory (it could also be any directory path),  the grep "i" means case insensitive, and the file pattern should be in quotes so the shell itself doesn't try to fill in the blanks for wildcards.)

2 comments: