Introduction

Hello! In this article, we’ll learn about the grep command.

grep is a command that searches for specific patterns in text files or command output. It’s super useful when you’re like “Where was that string in this file again?”, and it’s definitely one of the must-know commands for using Linux.

What is the grep Command?

grep stands for “Global Regular Expression Print” and is a command that searches files or text for lines matching a specified pattern (strings or regular expressions) and displays them.

It has tons of use cases - finding error messages in log files, locating specific settings in configuration files, searching for function names in code, and so much more.

Basic Syntax

1
grep [options] pattern [file...]

Main Options

Option Description
-i Ignore case (case-insensitive search)
-v Display lines that don’t match (inverted search)
-n Display line numbers
-c Count matching lines
-l Display only filenames with matches
-r Recursively search directories
-E Use extended regular expressions (same as egrep)
-w Match whole words only
-A num Display num lines after match
-B num Display num lines before match
-C num Display num lines before and after match

Usage Examples

1
grep "error" log.txt

Output:

1
2
error: connection failed
fatal error: out of memory

This displays all lines containing “error” from the log.txt file. This is the most basic usage.

1
grep -i "error" log.txt

Output:

1
2
3
Error: connection failed
ERROR: authentication failed
error: out of memory

Using the -i option matches “Error”, “ERROR”, “error” - all of them. Super convenient.

Example 3: Display with Line Numbers

1
grep -n "function" script.sh

Output:

1
2
3
5:function hello() {
12:function calculate() {
25:function cleanup() {

The -n option also displays line numbers. Useful when you want to know where things are.

Example 4: Display Non-Matching Lines

1
grep -v "^#" config.conf

Output:

1
2
3
server_name = localhost
port = 8080
debug = true

The -v option does inverted search. In this example, it displays lines that don’t start with # (comment lines).

Example 5: Count Matching Lines

1
grep -c "TODO" *.js

Output:

1
2
3
app.js:5
utils.js:12
index.js:3

Counts how many lines contain “TODO” in each file. Useful for checking the number of tasks.

Example 6: Display Filenames Only

1
grep -l "password" *.txt

Output:

1
2
config.txt
settings.txt

Displays only filenames with matches. Convenient when you want to know which files contain something.

1
grep -r "import React" ./src

Output:

1
2
3
./src/App.js:import React from 'react';
./src/components/Header.js:import React from 'react';
./src/components/Footer.js:import React from 'react';

The -r option searches everything under the ./src directory. Super convenient for searching the entire project.

Example 8: Search Using Regular Expressions

1
grep -E "^[0-9]{3}-[0-9]{4}$" phone.txt

Output:

1
2
090-1234
080-5678

The -E option enables extended regular expressions. This example searches for phone number patterns.

Example 9: Match Whole Words

1
grep -w "cat" animals.txt

The -w option matches whole words only. “cat” matches, but “category” doesn’t.

Example 10: Display Surrounding Lines

1
grep -C 2 "error" log.txt

Output:

1
2
3
4
5
10:Starting connection...
11:Connecting to server...
12:error: connection timeout
13:Retrying...
14:Failed to connect

-C 2 displays 2 lines before and after the match. Useful when you want to see the context around errors.

Example 11: Combine with Pipes

1
ps aux | grep "nginx"

Output:

1
2
root      1234  0.0  0.1  nginx: master process
www-data  1235  0.0  0.2  nginx: worker process

Filter the output of other commands with grep. I use this a lot.

Basic Regular Expression Patterns

Pattern Meaning
. Any single character
^ Beginning of line
$ End of line
* Zero or more of preceding character
+ One or more of preceding character (requires -E)
? Zero or one of preceding character (requires -E)
[abc] Any of a, b, c
[^abc] Any except a, b, c
[0-9] Digit
| OR (requires -E)

Tips & Notes

  • Use quotes: Wrap patterns containing spaces or special characters in quotes

    1
    
    grep "error message" log.txt
    
  • Characters that need escaping: Escape special characters like . or * with \ when searching for them literally

    1
    
    grep "192\.168\.1\.1" config.txt
    
  • Colored display: --color=auto highlights search results (default in many environments)

    1
    
    grep --color=auto "error" log.txt
    
  • Multiple pattern search: Use -e option to specify multiple patterns

    1
    
    grep -e "error" -e "warning" log.txt
    
  • Read patterns from file: Use -f option to read patterns from a file

    1
    
    grep -f patterns.txt log.txt
    

Practical Usage

Extract Errors from Log Files

1
grep -i "error\|warning\|critical" /var/log/syslog

Picks up all error-related messages from system logs. I use this a lot for troubleshooting.

Exclude Comments and Blank Lines from Config Files

1
grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"

Convenient when you only want to see actual settings in a config file. Excludes comment lines and blank lines.

Check Processes

1
ps aux | grep "[n]ginx"

A technique to exclude the grep process itself. The regex [n]ginx matches “nginx” but not this command’s own “[n]ginx”.

Search for Specific Code Across Multiple Files

1
grep -rn "function calculateTotal" ./src --include="*.js"

Can be used to find function definitions in JavaScript files within a project.

List All TODO Comments

1
grep -rn "TODO\|FIXME\|HACK" ./src

Lists all TODO comments in the codebase. Useful before refactoring.

Search Excluding Specific Extensions

1
grep -r "search_term" --exclude="*.min.js" --exclude-dir="node_modules" .

Searches while excluding minified files and node_modules. Reduces unnecessary results.

Summary

In this article, we learned about the grep command.

Key Points:

  • grep is a basic command for searching patterns in text
  • Use -i to ignore case, -n to display line numbers
  • Use -r to recursively search directories
  • Supports regular expressions for complex pattern searches
  • Combine with pipes to filter output from other commands

grep is truly an essential command for using Linux. You’ll use it constantly - for log investigation, code searching, and so many other scenarios. Try out the various options and get comfortable using it.

Keep learning Linux commands!