How to use Grep to Search in the Terminal

What is Grep?

Grep is a Unix and Linux command that searches a file for a particular pattern of characters.

It actually stands for globally search for regular expression and print out.

If you want to find all of the lines in a file that contain a particular string, grep is a helpful tool you can use without having to leave the terminal.

How to Use Grep

In a Unix or Linux environment, the grep command can be called in the terminal like so:

grep [options] [pattern] [files]
grep -r println .

Some commonly used options:

-r : Recursive search, looks in all files and directories.
-c : This prints only a count of the lines that match a pattern
-f file : Takes patterns from file, one per line.
-h : Display the matched lines, but do not display the filenames.
-l : Displays list of a filenames only.
-i : Ignores, case for matching
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-w : Match whole word
-o : Print only the matched parts of a matching line

For a full list of Grep options, check out the manual.

Example Usage of Grep

Let's say I'm working on a feature and want to remove references to a certain object, everywhere that it's called.

I can search my project for instances of this Foo object like so:

grep -r Foo .

This will perform a recursive search (the -r option) meaning it will search the given file and all subdirectories it encounters.

In this example my current directory contains a src directory that also leads to src/assets. Both of these will search all of their files for any like of code containing the work "Foo".

I can narrow down my search to a specific file or directory too.

grep -r console.log app/javascript/

The output will be a list of files containing the search patten and the instance of the pattern.

app/javascript//friendlist/people/PeopleEdit.jsx:          console.log(error);
app/javascript//components/DashboardContainer.js:    //console.log('component did mount')

And that's how to use Grep!

Level up faster
Recommended Books
Check out my list.
One on Ones: 101
Leveraging Other People's Experience
Hey, I'm Nicholas Dill.

I help people become better software developers with daily tips, tricks, and advice.

Level up
Related Articles
More like this
An Introduction to Your Terminal