Cogs and Levers A blog full of technical stuff

Text search with grep

GNU Grep is an amazingly powerful tool that will allow you to search input files containing specified patterns.

The following command performs a recursive search for a string, inside a directory of files:

grep -rnw '/path/to/search' -e 'pattern-to-find'

Breaking this command down:

  • -r makes the execution recursive
  • -n will give you the line number
  • -w matches the whole word

You can use the --exclude switch to remove file patterns from the set of files included in your search. Removing js and html files from your search might look like this:

--exclude *.{js,html}

The opposite of this will be the --include switch.

For further details on this really useful tool, check out the man page.