A Really Useful Git Command For Quickly Searching Text

A Really Useful Git Command For Quickly Searching Text

Β·

2 min read

In this article, we will see a very useful command to search for a particular text inside a project code.

Many times when working on code, you want to find out where in the repository a particular text is used, either to replace it with other text or for debugging purposes.

If you try to use a global search in your favorite IDE like Visual Studio Code or Sublime Text, you will get the text you are searching in hundreds or thousands of files including package.json, package-lock.json, and other unnecessary files.

Instead, you can use the git grep command to quickly search within files.

So let’s dive into it.


Suppose, you want to find the files in which a particular package like require("express") or require('express') is used. j

Just using a global search for express in VS Code will give many results, instead, we can run the following command from a terminal from your project folder:

git grep -n $'require([\'"]express[\'"]'

The above command will list out the filename, line number along with the matching text from that file.

This will produce the output as shown below:

express_output1.png


Suppose you want to find in which files, a particular property like http_mode from the app object is used.

In short, if you want to find the occurrence of .http_mode you can execute the following command:

git grep $'\.http_mode'

This will produce the output as shown below:

git_output.png


If you want to find the text NavLink only in a particular directory instead of all the directories, you can execute the following command:

grep -rn src/routes -e NavLink

This will produce the output as shown below:

git_output1.png

Thanks for reading!

Want to learn all ES6+ features in detail including let and const, promises, various promise methods, array and object destructuring, arrow functions, async/await, import and export and a whole lot more from scratch?

Check out my Mastering Modern JavaScript book. This book covers all the pre-requisites for learning React and helps you to become better at JavaScript and React.

Check out free preview contents of the book here.

Also, you can check out my free Introduction to React Router course to learn React Router from scratch.

Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.

Did you find this article valuable?

Support Yogesh Chavan by becoming a sponsor. Any amount is appreciated!