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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.