git grep – The Search Ninja
You might already be familiar with some of the search commands like find, grep etc. In this post, we are going to talk about git grep which is an amazing command to find contents within a git repository.
One thing to note here is that git grep only works for already tracked files. To include files which are present in a Git repo but are not being tracked by Git we need to pass the flag –untracked.
Why use git grep?
We all would agree that git is an amazing version control tool which helps us to keep track of things very efficiently. Among the several commands provided by git, when it comes to searching, I find git grep to be very useful. It is fast and provides some flags which are missing from any other search command. Let’s have a look at the command and some of the very useful flags in detail.
How to use git grep?
The git grep command is similar to grep -r command but it searches only in a git repository. Here is a list of commands along with some useful arguments that most the developers will find helpful –
// Search all lines matching demo
git grep demo
// Search content in files
git grep <regexp>
// Include line number in search result
git grep -n <regexp>
// List only the file names
git grep -l <regexp>
// Count the number of occurrences too
git grep -c <regexp>
// Limit the search to a specific file type
git grep <regexp> — ‘*.groovy’
// Search through a specific type of files in some branch. Anything after — are treated as limiters.
git grep -e <regexp> some_branch — ‘*.groovy’
// find all files which matches <regexp> in revisions ‘master’ and ‘b4b50c3rr’
git grep -l <regexp> master b4b50c3rr
// Search through indexed contents
git grep –cached -e <regexp>
// Search for files with multiple word match in a single line
git grep -e <regexp> –and -e <regexp>
// Search for files with multiple word match anywhere in file
git grep –all-matches -e <regexp> -e <regexp>
These are few of the many options that git grep provides.Visit the official documentation site to see other options.
By now, we have seen what git grep can do and how it makes our lives easier with its amazing capabilities. If you are not using it then you should certainly give it a try. For those who are already using it, please feel free to suggest other helpful commands in the comments below.
Hope this post helps you all the same way it has helped me.
About CauseCode: We are a technology company specializing in Healthtech related Web and Mobile application development. We collaborate with passionate companies looking to change health and wellness tech for good. If you are a startup, enterprise or generally interested in digital health, we would love to hear from you! Let's connect at firstname.lastname@example.org