The grep Command

Learn about the grep utility in detail.

We'll cover the following

Using grep

The GNU utilities have one more searching tool besides find, called grep. This utility checks file contents when searching.

How to choose the proper utility for searching

Use find for searching a file or directory by its name, path, or metadata. Metadata is extra information about an object. Examples of the file metadata are size, time of creation, last modification, and permissions. Use the grep utility to find a file when we know nothing about it except its contents.

The following example shows us how to choose the right utility for searching. Let’s suppose that we are looking for a documentation file. We know that it contains the phrase “free software”. If we apply the find utility, the searching algorithm looks like this:

  1. Call find to list all the files with the README name.
  2. Open each file in a text editor and check if it has the phrase “free software”.

Using a text editor for checking dozens of files takes too much effort and time. We should perform several operations with each file manually: open it, activate the editor’s searching mode, type the “free software” phrase. The grep utility automates this task. For example, the following command finds all lines with the “free software” phrase in the specified README file:

grep "free software" /usr/share/doc/bash/README

Parameters of grep

The first parameter of the utility is a string for searching. Always enclose it in double quotes. This way, we prevent Bash expansions and guarantee that the utility receives the string unchanged. Without the quotes, Bash splits the phrase into two separate parameters. This mechanism of splitting strings into words is called word splitting.

The second parameter of grep is a relative or absolute path to the file. If we specify a list of files separated by spaces, the utility processes them all. In the example, we passed the README file path only.

The -n option adds the line numbers to the grep output. It can help us check big text files. Add the option before the first parameter when calling the utility. We can write a command using the -n option as:

grep -n "free software" /usr/share/doc/bash/README

Run the commands discussed in this lesson in the terminal below.

Get hands-on with 1200+ tech skills courses.