Grep basics in 25 seconds

Well, not exactly 25 seconds, but I thought that would make a great title. I find I always have to introduce new junior devs to the world of grep and I think the following will get anyone started very quickly.

If you’re searching for a specific term or keywords within a million files, use this:

grep -ir pattern /path/to/search/

The -i switch stands for case insensitive and r is for recursive.

Another good search, especially within source code is:

grep -rn 'pattern' /path/to/search

This adds the line number to output so you can easily see where a variable or function is used.

If you ever need to search amongst a million files, with thousands of different extensions, but you’re only interested in specific file type, then you can try something like this:

find . -type f -name "*.php" | xargs grep -i pattern

That’ll give you very specific searches. The above, as an example, search only actual files that ends with ‘.php’.

If the tree you’re searching contains whitespace in the paths names you can use find … -print0 and xargs -0:

find . -type f -name "*.php" -print0 | xargs -0 grep -i pattern

To search multiple keywords use this:

find . -xdev -type f -name "*.php" | xargs grep -iHE "keyword1|keyword2"

Have fun!