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.
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!
`git grep` command is used to search in the checkout branch and local files.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With