How can I grep recursively, but only in files with certain extensions?

Using grep recursively

Just use the --include parameter, like this:

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.example

That should do what you want.

To take the explanation from HoldOffHunger’s answer below:

  • grep: command
  • -r: recursively
  • -i: ignore-case
  • -n: each output line is preceded by its relative line number in the file
  • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)
  • ./: Start at current directory.

ShareFollow

edited Jun 20, 2022 at 9:27

Stephen Ostermiller's user avatar

Stephen Ostermiller

22.8k1313 gold badges8686 silver badges105105 bronze badges

answered Sep 20, 2012 at 16:35

Nelson's user avatar

Nelson

48.4k88 gold badges6565 silver badges8181 bronze badges

Show 1 more comment

433

Some of these answers seemed too syntax-heavy, or they produced issues on my Debian Server. This worked perfectly for me:

grep -r --include=\*.txt 'searchterm' ./

…or case-insensitive version…

grep -r -i --include=\*.txt 'searchterm' ./
  • grep: command
  • -r: recursively
  • -i: ignore-case
  • --include: all *.txt: text files (escape with \ just in case you have a directory with asterisks in the filenames)
  • 'searchterm': What to search
  • ./: Start at current directory.

Source: PHP Revolution: How to Grep files in Linux, but only certain file extensions?

ShareFollow

edited Jun 17, 2020 at 4:04

answered Feb 8, 2016 at 22:46

HoldOffHunger's user avatar

HoldOffHunger

17.8k88 gold badges9494 silver badges127127 bronze badges

  • 9You should escape the * using \*.cpp or '*.cpp'. Otherwise it won’t give the expected result when the working directory contains some *.txt files. – Melebius Jan 2, 2017 at 7:17
  • @Melebius can you explain why it needs escaping – does it have anything to do with the CPP or TXT extensions you mentioned? Or did you just use those as examples? – Simon East Apr 28, 2017 at 3:05 
  • 2@SimonEast These extensions are those used in this question and answer, nothing special otherwise. It would probably work without escaping when using --include=<pattern> but it is important to escape * with --include <pattern> (a space instead of =) which feels very similar otherwise. – Melebius Apr 28, 2017 at 6:55
  • @Melebius adding to what you wrote, it does work with --include=<pattern>. It also works with --include<pattern>, so long as there are no files matching the pattern in the current directory. I.e., it’s safest to escape the pattern when you’re not using the = syntax, but you can live dangerously if you assume there are no files matching the pattern in the current directory. – TooTone Nov 4, 2021 at 22:02

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *