Page 1 of 1

Grep: Only certain filemask recursively in subfolders

PostPosted: Thu Dec 22, 2016 10:31 pm
by peter_b
Here are a few examples for grepping only files of a certain filetype (=matching a certain filemask) within subfolders:
(NOTE: Replace the string "MY_SEARCH" with your search expression accordingly)

1) Search "MY_SEARCH" in source code (*.cpp, *.h) files:
Code: Select all
$ grep -R "MY_SEARCH" --include *.{cpp,h} source/

Arguments:
-R: Recursive
--include: file pattern / filemask to include (the opposite would be "--exclude")
*.{cpp,h}: pattern to match *.cpp and *.h respectively.

2) Search case-insensitive in "*.php":
Code: Select all
$ grep -Ri "MY_SEARCH" --include *.php source/

Arguments:
-i: case insensitive

3) Show matching lines and their line numbers:
Code: Select all
$ grep -Rin "MY_SEARCH" --include *.php source/

Arguments:
-n: show line numbers of matching lines (next to filename)

4) Show only filenames that contain matches:
Code: Select all
$ grep -Ril "MY_SEARCH" --include *.txt source/

Arguments:
-l: Show only the matching filenames. Not the actual strings/lines.


Might come in handy.
At least they do for me ;)