Including and excluding files in a grep search

grep can include or exclude files in which to search with wild card patterns.

To recursively search only for the .c and .cpp files, use the -include option:

    $ grep "main()" . -r  --include *.{c,cpp}

Note that some{string1,string2,string3} expands as somestring1 somestring2 somestring3.

Use the -exclude flag to exclude all README files from the search:

    $ grep "main()" . -r --exclude "README" 

The --exclude-dir option will exclude the named directories from the search:

    $ grep main . -r -exclude-dir CVS

To read a list of files to exclude from a file, use --exclude-from FILE.

Get Linux Shell Scripting Cookbook - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.