logo
search
list

Table of Content

What Grep Does (and Does Not)
Basic Grep Examples
Recursive Search (Ask Ubuntu Favorite)
Case, Whole Word, Invert, Count
Show Context Around Matches
Regular Expressions with Grep
Limit Which Files Are Searched
Grep with Pipes and Other Commands
Exit Status (Scripts)
Common Grep Mistakes
Quick Cheat Sheet
From Search Results to Shareable Notes
FAQ

Grep Command in Linux: Search Text Fast (Examples)

Posted by Algirdas Jasaitis

calendar

2026-08-12

views

876

likes

5

The grep command in Linux searches files (or standard input) for lines that match a pattern and prints those matches. On Ubuntu and other GNU/Linux systems, the usual form is:

grep [OPTIONS] PATTERN [FILE...]

Quote the pattern in the shell. If you give no file and are not searching recursively, grep reads standard input. Success means matching lines appear (exit status 0), or nothing prints when there is no match (exit status 1).

This guide follows the Ubuntu/GNU grep man page and the highest-traffic Ask Ubuntu patterns—especially recursive search with -r / -rl / -Hrn.

If you already know your goal, jump to: recursive search, case-insensitive, invert match, regex, or exclude binary/.git.

New to the shell? Start with essential Linux commands, or keep the commands cheat sheet open while you practice.

Concept illustration of the Linux grep command searching and highlighting text in a terminal
Use grep to find matching lines in files—add -r for subdirectories, -i for case-insensitive, and -n for line numbers.

What Grep Does (and Does Not)

  • Does: print matching lines (unless you ask for counts, filenames only, or matched pieces with -o)
  • Does not: edit files in place (use sed/awk for edits)
  • Default regex: basic regular expressions (BRE); use -E for extended, -F for fixed strings, -P for Perl-compatible (where available)

Debian/Ubuntu still ship egrep / fgrep / rgrep as shortcuts for grep -E / grep -F / grep -r, but the man page recommends preferring grep with those options for portability.

Basic Grep Examples

# Search one file
grep "error" /var/log/syslog

# Search several files
grep "TODO" notes.txt todo.md

# Read from a pipe
ps aux | grep firefox

# Pattern starts with a dash — use -e
grep -e "-v" script.sh

Recursive Search (Ask Ubuntu Favorite)

The classic Ask Ubuntu question is how to search subdirectories. Use -r (or --recursive):

# Search current directory tree
grep -r "search term" .

# Filenames only (stops at first match per file — often faster)
grep -rl "search term" /path

# Filename + line number (very common developer combo)
grep -Hrn "search term" /path/to/files

Ask Ubuntu’s top answers highlight:

  • -r / --recursive — walk subdirectories
  • -l / --files-with-matches — print matching filenames only
  • -H — always show the filename (implied when multiple files)
  • -n — show line numbers
  • . — search from the current directory

-r vs -R: -r follows symlinks only if they appear on the command line; -R follows all symlinks while recursing.

Case, Whole Word, Invert, Count

OptionMeaning
-iIgnore case
-wMatch whole words
-xMatch whole line
-vInvert — show non-matching lines
-cCount matching lines per file
-oPrint only the matched part
-m NUMStop after NUM matches per file
-qQuiet — exit status only (scripts)
grep -i "error" app.log
grep -w "root" /etc/passwd
grep -v "^#" config.conf          # drop comment lines starting with #
grep -c "Failed" /var/log/auth.log
grep -q "ready" status.txt && echo "found"

Show Context Around Matches

grep -A 3 "Exception" app.log     # 3 lines after
grep -B 2 "Exception" app.log     # 2 lines before
grep -C 2 "Exception" app.log     # 2 lines before and after

Useful when reading stack traces or config blocks.

Regular Expressions with Grep

Default is BRE. For |, +, ?, and unescaped ()/{}, prefer extended regex (-E):

# Either pattern (ERE)
grep -E "error|warning|critical" app.log

# Fixed string — no regex metacharacters (safer for user input)
grep -F "C:\Users\name" notes.txt

# Multiple patterns
grep -e "error" -e "fatal" app.log
grep -f patterns.txt app.log      # one pattern per line in file

Ask Ubuntu note: \t often does not mean “tab” in basic grep the way people expect—search for a real tab character, use [[:space:]], or tools that understand escapes depending on your grep build/-P.

Spaces in patterns: quote them — grep "hello world" file.

Limit Which Files Are Searched

# Only certain extensions
grep -rn "TODO" . --include="*.py" --include="*.js"

# Skip junk
grep -rn "password" . --exclude="*.min.js" --exclude-dir=".git" --exclude-dir="node_modules"

# Ignore binary matches (don’t spam “Binary file matches”)
grep -rI "API_KEY" .
OptionMeaning
--include=GLOBOnly basenames matching GLOB
--exclude=GLOBSkip matching files
--exclude-dir=GLOBSkip matching directories
-ITreat binary as non-matching
-aTreat binary as text (can garble the terminal)

Non-recursive search of files in one directory only (Ask Ubuntu nuance): put the files on the command line (for example grep pat *) or combine find carefully—plain grep -r always descends.

Grep with Pipes and Other Commands

Grep filters lines; to rewrite matches use sed, and to split columns use awk.

# Filter command output
dmesg | grep -i usb

# List only matching filenames, then edit
grep -rl "oldName" src/ | xargs sed -i 's/oldName/newName/g'   # review before mass edit

# Search compressed logs
zgrep -i "error" /var/log/syslog.2.gz

Exit Status (Scripts)

StatusMeaning
0At least one line selected
1No lines selected
2Error (bad option, unreadable file, etc.)

With -q, a match still yields 0 even if some errors occurred (see man page).

Common Grep Mistakes

  1. Forgetting quotes — the shell may expand * or spaces before grep runs
  2. Expecting egrep forever — prefer grep -E
  3. Recursive from / without excludes — slow and noisy; start from a project path
  4. Treating - patterns wrong — use grep -e '--flag'
  5. Binary file noise — add -I or --include for source trees
  6. Assuming \t works — verify with your grep/regex mode

Quick Cheat Sheet

grep -rn "pattern" .                 # recursive + line numbers
grep -ri "pattern" .                 # recursive, ignore case
grep -rl "pattern" /path             # matching filenames only
grep -rn "pattern" . --include="*.c" # recursive in .c files
grep -v "^$" file                    # drop empty lines
grep -E "a|b" file                   # extended OR
grep -F '1+1=2' file                 # literal string
grep -C2 "pattern" file              # context
man grep                             # full reference

From Search Results to Shareable Notes

grep finds the exact lines you need in configs, code, and logs. The next step is often copying those findings into a report, a checklist, or a quick handoff note.

WPS Office for Linux is useful for that handoff: paste the matched lines into Writer, summarize them in a spreadsheet, or export a PDF for someone who does not live in the terminal.

WPS Office Writer on a Linux desktop editing an incident report DOCX with a familiar ribbon toolbar
WPS Writer on Linux: turn setup notes, terminal findings, and troubleshooting steps into a DOCX or PDF that teammates can open easily.
What you need nextWhat WPS gives you
Turn matched lines into a document or reportStrong .docx / .xlsx / .pptx layout fidelity when files move between Linux, Windows, and macOS
One place for notes, sheets, slides, and PDFsFree core suite: Writer, Spreadsheet, Presentation, plus PDF view/edit/convert tools
A familiar desktop UI for switchersRibbon-style apps with a lighter footprint than many heavy suites
A trusted install pathOfficial DEB (Ubuntu/Debian/Mint) and RPM packages from the vendor

Get the current build from the official WPS Office for Linux download page, then install the local package with sudo apt install ./wps-office_VERSION_amd64.deb. Keep grep for finding text; use WPS when those results need to become a shareable document.

FAQ

What is the grep command in Linux used for?
To search for text patterns in files or command output and print matching lines.

How do I grep recursively in Linux?
grep -r "pattern" /path or grep -rn "pattern" . for line numbers. Use grep -rl for filenames only.

How do I make grep case-insensitive?
Add -i: grep -i "error" file.log.

What is the difference between grep -r and grep -R?
Both recurse; -R also follows symbolic links under directories, while -r follows symlinks only when given on the command line.

How do I grep multiple patterns?
grep -e pat1 -e pat2 file, or grep -E 'pat1|pat2' file, or grep -f patterns.txt file.

Where can I read the official options?
Run man grep or open the Ubuntu man page for grep on manpages.ubuntu.com.

Algirdas Jasaitis

15 years of office industry experience, tech lover and copywriter. Follow me for product reviews, comparisons, and recommendations for new apps and software.