Grep: Only certain filemask recursively in subfolders

Step-by-Step descriptions of how to do things.
Post Reply
User avatar
peter_b
Chatterbox
Posts: 331
Joined: Tue Nov 12, 2013 2:05 am

Grep: Only certain filemask recursively in subfolders

Post 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 ;)
Post Reply