Since a long time, I have been using the grep utility to search in code, and I am pretty comfortable with the tool. However, recently I came across git grep. The main advantage of this tool, when compared with the normal grep, is the speed of search. Read on to know how to use git grep to speed up development and coding.
There is a huge difference in the search speed when compared to the normal grep utility. Yet another advantage is that you do not have to sort out the data related to the project. As there may be testing files or other untracked files in projects folder, using grep will bring unwanted results in those untracked files too. However, in the case of git grep, since we are only searching in the current code base, results would be completely relevant to the current project you are working on.
Here, I will introduce some awesome options provided by the git grep utility.
-i or --ignore-case
This will perform the search without considering the case of the search keyword.
-n or --line-number
It will display the line number with the matched line.
It shows the matched lines from different files with a line break between them.
The filename is displayed as a heading for the matches from a single file.
Indicates the end of the options, preceding will be the <pathspec> limiters, by which we can limit our searches to particular files types
-c or --count
Instead of showing all the results, it shows the number of lines that match.
As you can see the git grep provides enough options and functionalities that will make your code search more easier and faster. Some usage examples are,
- git grep "string to search" -> Will search the string in the complete code base.
- git grep -ni "string to search" -> Will list the matches without considering the case of string along with line numbers.
- git grep --break "search string" -> Will list the matches from different files with a line break in between.
- git grep "search string" -- *.php -> This will search only the files with extension .php. You can specify multiple file types by using a space in between.