Skip to content

Linux commands: grep

New Course Coming Soon:

Get Really Good at Git

A quick guide to the `grep` command, used to match patterns in text

The grep command is a very useful tool, that when you master will help you tremendously in your day to day.

If you’re wondering, grep stands for global regular expression print

You can use grep to search in files, or combine it with pipes to filter the output of another command.

For example here’s how we can find the occurences of the document.getElementById line in the index.md file:

grep -n document.getElementById index.md

Using the -n option it will show the line numbers:

grep -n document.getElementById index.md

One very useful thing is to tell grep to print 2 lines before, and 2 lines after the matched line, to give us more context. That’s done using the -C option, which accepts a number of lines:

grep -nC 2 document.getElementById index.md

Search is case sensitive by default. Use the -i flag to make it insensitive.

As mentioned, you can use grep to filter the output of another command. We can replicate the same functionality as above using:

less index.md | grep -n document.getElementById

The search string can be a regular expression, and this makes grep very powerful.

Another thing you might find very useful is to invert the result, excluding the lines that match a particular string, using the -v option:

The grep command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: