Skip to main content
Searching for text patterns across files and directories is a common task on Linux systems. The grep command lets you quickly locate lines that match a specified string or regular expression.

Table of Common Options


General Syntax

  • PATTERN
    The text or regular expression to search for.
  • FILE
    One or more files or directories to scan. If no file is given, grep reads from standard input.
Always quote patterns that contain spaces or shell metacharacters:

By default, grep performs a case-sensitive search. To find lines containing CentOS in /etc/os-release:

Use -i to ignore case differences. This matches “centos”, “CentOS”, or “CENTOS” alike:

3. Recursive Search in Directories

To search through all files in a directory and its subdirectories, combine -r with your pattern:
Combine -r and -i for a recursive, case-insensitive search:
You may encounter “Permission denied” messages when scanning protected directories. Use sudo if you need elevated privileges:

4. Invert Match

Show only the lines that do not contain the pattern. Use the -v option:

5. Match Whole Words Only

To avoid matching substrings (e.g., “redhat” when you want “red”), add the -w flag:

6. Show Only the Matched Text

By default, grep prints the entire line containing the match. Use -o to display only the portion that matches:

You’ve now covered the essentials of grep for searching text in files. In upcoming lessons, we will explore more advanced text-processing tools like awk and sed.

Watch Video