Using regex in find command for multiple file types

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 involves two teams, it seems ineffective.

How can I use one regex pattern to search for .c, .C, .h, .H, .cc and .CC files?

I am using bash on a Linux machine.

+6
source share
4 answers

You can use the logical argument OR:

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

The above search looks in the current directory and in all subdirectories for files ending in:

  • .c , .h OR
  • .c , .h OR
  • .cc OR
  • .CC .
+15
source

This should work

Messy

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

-iregex for -iregex pattern without -iregex case.

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


clean

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

It will also find the extensions .Cc and .cC. You have been warned.

+11
source

This command is working.

 find -regextype posix-extended -regex '.+\.(h|H|c{1,2}|C{1,2})$' 

I would like to use iregex . iregex will also find .Cc and .Cc . If I could, the team would look like this. A bit shorter.

 find -regextype posix-extended -iregex '.+\.(h|H|c{1,2})$' 
+2
source

find . -regex '.*\.\([chCH]\|cc\|CC\)'
will find all files with names ending in .c, .C, .h, .H, .cc and .CC and will not find them in .hc, .cC or .Cc. In a regular expression, the first few characters correspond to the last period in the name, and alternatives in brackets correspond to any of the single characters c, h, C or H or cc or CC.

Note. Finding -regex and -iregex switches is similar to -name and -iname , but regular expression type switches allow you to use regular expressions with | for alternate matches. Like -iname , -iregex not -iregex .

(non-functional) form
find . -name '*.[cCHh][cC]?$'
given in the previous answer does not contain any names on my Linux system with GNU find 4.4.2. Another problem with '*.[cCHh][cC]?$' As a regular expression is that it will match names like abc.Cc and xyz.hc that are not part of the .c, .C, file set. h, .H, .cc and .CC that you want.

0
source

Source: https://habr.com/ru/post/928093/


All Articles