Skip to main content

grep — Search Inside Files in Linux

Introduction

grep is one of the most fundamental and powerful text-search tools in Linux. It scans files or input streams for matching text patterns and prints the lines that contain those matches.

Tool Snapshot
  • Core Function: Universal text pattern matching through content scanning.
  • Primary Benefit: Ubiquitous availability and seamless integration with Linux pipes.
  • Where to Use: Log debugging, searching within specific files, and basic pattern matching.
  • Logic: Reads file contents directly or from stdin.

Unlike locate or fd, which search by filename, grep searches inside file contents.

It is commonly used for:

  • Log analysis
  • WordPress debugging
  • Configuration inspection
  • SQL dump review
  • Malware scanning
  • Automation and scripting

grep works efficiently on large text files and integrates seamlessly with pipelines.

Prerequisites

  • Linux VPS (Ubuntu or similar)
  • Basic understanding of file paths (/var/log/, /var/www/html/)
  • Familiarity with text files (PHP, logs, configs, SQL dumps)
  • WordPress environment (for practical examples)

Syntax & Expression Rules

The command follows a logical structure that reads almost like a sentence:

grep [OPTION] PATTERN [FILE...]
  • [OPTION]: Flags to modify behavior (e.g., -i for ignore case, -r for recursive).
  • [PATTERN]: The text or regex to search for.
  • [FILE]: One or more files to search (if omitted, reads from stdin).

Pattern Types

PATTERN may be plain text or regular expression.

Plain Text

grep "index.php" wp-config.php

Matches exact text.

grep -i "error" error.log

Fixed String (No Regex Interpretation)

grep -F "a+b" file.txt

Treats special characters literally.

Basic Regex (Default)

PatternMeaning
--
.Any single character
*Zero or more of previous character
[]Character class
[^]Negated class
^Start of line
$End of line

Extended Regex (-E)

grep -E "cat|dog" file.txt

Adds support for:

  • |
  • +
  • ?
  • ()

Perl-Compatible Regex (-P)

grep -P "\d{4}-\d{2}-\d{2}" error.log

Supports:

  • \d, \w, \s
  • Lookaheads/lookbehinds
  • Advanced repetition

Availability depends on system build.

Core Options

Basic Matching

OptionDescription
--
-iIgnore case
-vInvert match
-wMatch whole word
-xMatch entire line

Output Control

OptionDescription
--
-nShow line numbers
-HShow filename
-hHide filename
-cCount matches
-oPrint only matching text
-qQuiet mode (exit code only)
--color=autoHighlight matches

Context Control

OptionDescription
--
-A NUMShow NUM lines after match
-B NUMShow NUM lines before match
-C NUMShow NUM lines around match

Recursive & File Filters

OptionDescription
-
-rRecursive search
-RRecursive + follow symlinks
--include=GLOBInclude matching files only
--exclude=GLOBExclude files
--exclude-dir=DIRExclude directory
-m NUMStop after NUM matches
--textTreat binary as text

Working with Files

Single File

grep "define" wp-config.php

Multiple Files

grep "index" *.php
grep -r "pattern" wp-content/

Recursive with File Filter

grep -r --include="*.php" "add_action" wp-content/

Exclude Directory

grep -r --exclude-dir=cache "define" wp-content/

Piped Input

cat error.log | grep "error"

Pattern List from File

grep -f patterns.txt file.txt

WordPress / VPS Examples

1. Search WordPress config

grep "define" wp-config.php
grep -i "error" /var/log/nginx/error.log

3. Count total errors

grep -c "error" error.log

4. Show line numbers

grep -n "DB_USER" wp-config.php

5. Whole-word match

grep -w "admin" users.txt

6. Invert match

grep -v "cache" plugins.txt

7. Match start of line

grep "^define" wp-config.php

8. Match end of line

grep "php$" filelist.txt

9. Recursive plugin scan

grep -r "wp_enqueue_script" wp-content/

10. Extract URLs only

grep -o "https://[a-zA-Z0-9./]*" index.php

11. Show context after match

grep -A2 "DB_NAME" wp-config.php

12. Show context around match

grep -C1 "DB_NAME" wp-config.php

13. Quiet check for automation

grep -q "DB_PASSWORD" wp-config.php && echo "Found"

14. Malware scan for eval usage

grep -r "eval(" wp-content/plugins/

15. Stop after first match

grep -m1 "error" error.log

16. Force text mode

grep --text "php" backup.img

Benefits

  • Fast text searching inside files
  • Powerful regex support
  • Works seamlessly with pipelines
  • Essential for debugging and auditing
  • Lightweight and universally available

Best Practices

  • Use -i when case does not matter.
  • Use -r with --include to limit search scope.
  • Combine with less for large outputs:
grep "error" log.txt | less
  • Use -q in scripts for silent checks.
  • Use -F for literal strings to improve performance.
  • Add --color=auto for easier visual scanning.

Troubleshooting Matrix

ProblemCauseSolution
---
No resultsCase mismatchAdd -i
Too many resultsBroad patternUse -w or refine regex
Slow performanceLarge directory treeAdd --include filter
No line numbers in pipeOutput to non-TTYAdd -nH
Binary file warningsFile treated as binaryUse --text

Cheat Sheet

grep "pattern" file.txt
grep -i "error" error.log
grep -n "define" wp-config.php
grep -r "pattern" dir/
grep -c "error" log.txt
grep -A2 "pattern" file.txt
grep -o "https://.*" file.txt
grep --color=auto "error" log.txt

Mini Quiz

  1. What does grep -i do?
  2. How do you search recursively only in .php files?
  3. What is the difference between -v and -w?
  4. How do you display 3 lines after a match?
  5. Which option prints only the matched text?