Linux command line: recursively find all files with a given string

Posted by jason on Nov. 4, 2011, 6:25 a.m.
Tags: bash linux programming

Here's a little script I wrote that I install on any linux server that I do any programming on:

find . -type f -iregex '.*\.\(php\|html\|js\|css\|py\|lua\)$' -print0 | xargs -0 grep -n -i -H "$1"

Note that this searches all .php, .html, .js, .css, .py, and .lua files (the extensions being case-insensitive). Feel free to add / remove whatever you like.

Save that block of code into a file called "mysearch", then copy mysearch to /usr/local/bin/ and run "chmod +x" on it.

Usage: run "mysearch " to search the current working directory recursively for the given term. Put the search term in quotes if you need to search for multiple words--e.g., mysearch "function validate".

Tip #1: I like to add the following line to my .bashrc file for coloured output:

export GREP_OPTIONS='--color=auto'

Tip #2: Sometimes I get matches from javascript files that I don't care about (like a minified jquery file, for example). The quick-and-dirty solution is to filter out some of the results by piping the output to "grep -v", like so:

[jason@jason ~]$ mysearch "function init" | grep -v jquery.js