Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 16

Searching with Grep

Recommended resources

Hello! Welcome back to the "Text Processing and File Searching" module.

In the last lesson, you learned how to view the contents of files using cat, less, head, and tail. These tools are perfect for when you know which file you want to read. But what if you need to find a specific piece of information buried within dozens or even hundreds of files?

This is where grep comes in. It's one of the most powerful and frequently used commands in the Linux toolkit. This lesson will teach you how to search for text patterns within files using grep. We'll start with simple text searches, explore essential options to refine your results, and then touch upon the real power of grep: regular expressions. Mastering this command is a crucial step towards passing the CompTIA Linux+ exam and becoming a proficient system administrator.

1. What is grep? Basic Searching

grep stands for Global Regular Expression Print. Its job is to search for a specified pattern in text and print the lines that contain a match. You can provide this text from a file or from the output of another command.

Basic Syntax

The most common way to use grep is:
grep 'pattern' filename

Let's start with a video that introduces the grep command, compares the common (but redundant) practice of piping from cat, and shows the more direct method.

Linux Crash Course - The grep Command

This video from Learn Linux TV will explain what grep is and show you the fundamental ways to use it. Pay attention to the difference between cat /file | grep 'pattern' and the more efficient grep 'pattern' /file.

Watch from 02:06 to 03:56 and then from 04:44 to 05:33. The section in between will be covered next.


2. Refining Your Search with Common Options

While a basic search is useful, grep's real utility comes from its many options (flags) that modify its behavior. Here are some of the most essential ones you'll use daily.

  • -i (ignore case): Performs a case-insensitive search.
  • -v (invert match): Selects non-matching lines.
  • -n (line number): Shows the line number of each match.
  • -c (count): Displays a count of matching lines instead of the lines themselves.

The next segment of the video you started watching covers these key options.

Linux Crash Course - The grep Command

Let's continue with the Learn Linux TV video to see these common options in action.

Watch from 03:56 to 04:44 and then from 07:33 to 09:02. You will see demonstrations of the -v, -n, -c, and -i options.

Test your understanding!

You are examining the /etc/passwd file, which contains user account information. You want to find all users that do not have /bin/bash assigned as their login shell, and you want to see the line numbers for these entries.

Which of the following commands would you use?

  1. grep -c '/bin/bash' /etc/passwd
  2. grep -in '/bin/bash' /etc/passwd
  3. grep -vn '/bin/bash' /etc/passwd
  4. grep -v '/bin/bash' /etc/passwd
Show answer

The correct answer is 3. grep -vn '/bin/bash' /etc/passwd.

  • -v is used to invert the match, showing lines that do not contain /bin/bash.
  • -n is used to display the line numbers for the matching (or in this case, non-matching) lines.
  • Options can be combined, so -vn is correct.

3. Expanding the Scope of Your Search

Sometimes you need to search more than just a single file. grep makes it easy to search across multiple files, directories, and even entire directory trees.

  • Searching multiple files: You can use wildcards, just as you did with file management commands. For example, grep 'error' *.log will search for "error" in all files ending with .log in the current directory.
  • Recursive search (-r): This is one of the most useful options. It tells grep to search in the specified directory and all of its subdirectories. This is perfect for finding a configuration setting when you're not sure which file it's in.

The following video segments demonstrate these powerful techniques, including a real-world example of searching system log files.

Linux Crash Course - The grep Command

This last segment from the Learn Linux TV video shows how to use wildcards and the -r option for recursive searching.

Watch from 10:03 to 13:14. Notice how grep -r can quickly find a term across many files and subdirectories, and see the practical example of searching for "error" in /var/log.

Grep Command Examples in Linux Terminal
This terminal screenshot shows several practical examples of `grep` in action, including searching files like `/etc/passwd`, using pipes, and using `egrep` for more complex patterns.

4. Controlling the Output and Match Specificity

Beyond just finding a match, you often need to control how grep matches and what context it shows you.

  • -w (word regexp): Matches only whole words. grep -w 'open' will match open but not opensource.
  • -A, -B, -C (context): Displays lines After, Before, or around (Context) the matching line. For example, grep -A 2 'error' shows the matching line plus the two lines after it, which is invaluable for debugging logs.

This next video provides clear demonstrations of these options.

grep: A Practical Guide

This video from Navek provides a practical guide to some more advanced grep features. We'll focus on word matching and viewing context.

Watch from 03:35 to 04:22 to understand -w, and from 05:45 to 07:21 to see how -A, -B, and -C work.


5. An Introduction to Regular Expressions

The "re" in grep stands for Regular Expression (regex). A regular expression is a sequence of characters that specifies a search pattern. Using regex unlocks grep's true potential, allowing you to search for complex and variable patterns, not just fixed strings.

Here are a few of the most fundamental regex metacharacters:

  • ^: Anchors the pattern to the start of a line. ^root matches lines that begin with "root".
  • $: Anchors the pattern to the end of a line. nologin$ matches lines that end with "nologin".
  • []: Defines a character set. [0-9] matches any single digit. [aeiou] matches any vowel.
  • |: Acts as an "OR" operator. error|warning matches lines containing either "error" or "warning".

When using characters like |, you often need to use grep -E (for Extended regex), which is often aliased as egrep. This tells grep to interpret these special characters without needing to escape them with a backslash.

The following resources will give you a solid introduction to using regex with grep.

grep: A Practical Guide

Let's return to the Navek video to see how to use basic regular expressions for anchoring and character ranges.

Watch from 07:21 to 09:36 to see ^ and $ in action. Then, watch from 11:33 to 12:26 to understand how extended regex (-E) and character ranges ([0-9]) work.

For a more detailed textual explanation and further examples, the following article provides an excellent foundation.

A beginner's guide to regular expressions with grep

This article from Red Hat Developers, "A beginner's guide to regular expressions with grep," dives into the core concepts of regex. It's a great reference to solidify your understanding.

Read the sections "Regular characters, metacharacters, and patterns" to understand the building blocks. Then, review the examples under "Running basic regular expressions," paying special attention to the examples for logical patterns (|), beginning of line (^), and end of line ($).

Test your understanding!

You need to find all lines in the /etc/services file that describe services running on ports that start with the digit 8. Which grep command would accomplish this?

(Hint: Service definitions in this file typically have the service name, then the port number, like http 80/tcp.)

  1. grep '8' /etc/services
  2. grep -E '^8' /etc/services
  3. grep -E '\s8[0-9]*/' /etc/services
  4. grep '$8' /etc/services
Show answer

The best answer is 3. grep -E '\s8[0-9]*/' /etc/services.

  • \s matches the space character before the port number.
  • 8 matches the literal digit 8.
  • [0-9]* matches zero or more additional digits that might follow.
  • / matches the slash after the port number.
  • grep -E is used to ensure the extended regex is interpreted correctly.

While grep '8' /etc/services might work, it would also match lines with an 8 anywhere, not just at the start of the port number, making it less precise.


Conclusion

You have now learned how to use grep, one of the cornerstones of Linux text processing. From simple string searches to complex pattern matching with regular expressions, grep is an indispensable tool for finding information and troubleshooting issues.

Key Takeaways:

  • grep is used to search for text patterns in files or command output.
  • The basic syntax is grep [options] 'pattern' [filename].
  • Essential options include -i (ignore case), -v (invert), -n (line numbers), -c (count), and -r (recursive).
  • Options like -w (whole word) and -A/-B/-C (context) help you refine search results.
  • Regular Expressions (^, $, [], |) transform grep into a highly flexible pattern-matching engine. Use grep -E for extended regex features.

In our next lesson, we'll look at a different kind of searching. While grep is for searching inside files, the locate command is designed to find the files themselves, using a pre-built database for lightning-fast lookups.