Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to git grep only a set of file extensions

How do you perform a git grep and limit the files checked to a set of files. I would like to be able to grep the contents of .cpp and .h files looking for MyFunc. eg:

git grep "MyFunc" -- *.[hc]*

However this also matches, .c files and .cs files.

like image 488
stk_sfr Avatar asked Feb 06 '14 09:02

stk_sfr


People also ask

How do I grep for a specific file extension?

The syntax of grep needs to follow grep [OPTIONS…] PATTERNS [FILE…] where the PATTERN is what the text in the FILE must match: $ grep "Hello" * grep: Test: Is a directory test.cc:Hello World!

What files are searchable by git grep?

`git grep` command is used to search in the checkout branch and local files.

Which statement is the best comparison between git grep and grep?

The git grep version will only search in files tracked by git, whereas the grep version will search everything in the directory. So far so similar; either one could be better depending on what you want to achieve.

How do you grep a file name?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.


2 Answers

Use:

git grep "MyFunc" -- '*.cpp' '*.h'

The quotes are necessary so that git expands the wildcards rather than the shell. If you omit them, it'll only search files in the current directory, rather than including subdirectories.

like image 87
John Mellor Avatar answered Oct 01 '22 11:10

John Mellor


This can be achieved when using git bash in Windows by using:

git grep "MyFunc" -- *.{cpp,h}

or even simpler:

git grep "MyFunc" -- *.cpp *.h

The explanation of pathspec on the git glossary mentions that patterns are matched using fnmatch(3). Which matches patterns (including multiple characters) as described by Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13.1 and leads to basic regular expressions matching multiple characters and gave me the first solution.

Further research lead me to the second solution by looking into documentation on glob.

like image 7
stk_sfr Avatar answered Oct 01 '22 10:10

stk_sfr