Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex in find command for multiple file types [duplicate]

I am currently using

find . -name '*.[cCHh][cC]' -exec grep -nHr "$1" {} ; \
find . -name '*.[cCHh]' -exec grep -nHr "$1" {} ;

to search for a string in all files ending with .c, .C, .h, .H, .cc and .CC listed in all subdirectories. But since this includes two commands this feels inefficient.

How can I use a single regex pattern to find .c,.C,.h,.H,.cc and .CC files?

I am using bash on a Linux machine.

like image 518
Arpith Avatar asked Oct 19 '12 07:10

Arpith


2 Answers

You can use the boolean OR argument:

find . -name '*.[ch]' -o -name '*.[CH]' -o -name '*.cc' -o -name '*.CC'

The above searches the current directory and all sub-directories for files that end in:

  • .c, .h OR
  • .C, .H OR
  • .cc OR
  • .CC.
like image 141
rid Avatar answered Sep 23 '22 00:09

rid


This should work

Messy

find . -iregex '.*\.\(c\|cc\|h\)' -exec grep -nHr "$1" {} +

-iregex for case-insensitive regex pattern.

(c|cc|h) (nasty escapes not shown) matches c, cc, or h extensions


Clean

find -regextype "posix-extended" -iregex '.*\.(c|cc|h)' -exec grep -nHr "$1" {} +

This will find .Cc and .cC extensions too. You have been warned.

like image 31
doubleDown Avatar answered Sep 23 '22 00:09

doubleDown