Leveraging the Linux grep Command for Web Development
Although the Linux command line can seem intimidating at times, it holds the power to greatly improve our productivity as web developers. In this article, I cover one of my all-time favorite Linux commands - the grep
utility.
Using grep
to Search for Strings
The grep
command lets users find strings in files. Computer scientist Ken Thompson (who also helped create the Golang programming language), originally authored the grep
utility in 1973, and grep
continues to be an integral part of Unix operating systems today. Its basic usage is like this
grep someWord someFile.txt
The above command searches inside someFile.txt for all occurrences of the word "someWord". The grep
command will then print each line where a match for "someWord" was found to the terminal. In this example, grep
is case sensitive. Therefore, "sOmEword" and "someword" will not be matches. To get a case-insensitive match, we can add in the -i
flag like this
grep -i someWord someFile.txt
and this can sometimes come in handy.
Why I Love grep
So why is grep
useful to us as developers you might ask? The grep
command can be helpful for both working in our own projects, and in someone else's codebase.
For example, in web development, I frequently write out JavaScript console.log
statements to check the expected behavior of variables. Although I usually remove these when I'm done testing something, before deploying an application, I like to double check that I have not left any console.log
statements in any of my files. To do this, I use the following grep
command from the main directory of the project I'm working on:
grep -rl 'console.log' --exclude-dir=node_modules ./*
This grep
command recursively (via the r flag) searches all files below the current working directory for "console.log", and prints to the terminal a list (using the l flag) of all files that contain a match. Pretty cool, right? But what if in addition to node_modules
, you also don't want to search in .git
and .cache
? You can just add those in brackets to form a glob with the exclude flag like this
grep -rl 'console.log' --exclude-dir={node_modules,.git,.cache} ./*
Then grep
will also not search in the .git
and .cache
folders.
While the above examples focus on how we might use grep
in searching for a console.log
statement, I've found grep
to be incredibly useful when learning a new codebase to see where some function is being used, tracking down software bugs based on an error message, and finding files using a string that needs to be renamed during a code refactor. This last example in particular lays the framework on how grep
can be combined with another powerful Linux command - the sed
utility, which I intend to discuss in a future article.