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.

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/awkfor edits) - Default regex: basic regular expressions (BRE); use
-Efor extended,-Ffor fixed strings,-Pfor 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
| Option | Meaning |
|---|---|
-i | Ignore case |
-w | Match whole words |
-x | Match whole line |
-v | Invert — show non-matching lines |
-c | Count matching lines per file |
-o | Print only the matched part |
-m NUM | Stop after NUM matches per file |
-q | Quiet — 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" .
| Option | Meaning |
|---|---|
--include=GLOB | Only basenames matching GLOB |
--exclude=GLOB | Skip matching files |
--exclude-dir=GLOB | Skip matching directories |
-I | Treat binary as non-matching |
-a | Treat 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)
| Status | Meaning |
|---|---|
0 | At least one line selected |
1 | No lines selected |
2 | Error (bad option, unreadable file, etc.) |
With -q, a match still yields 0 even if some errors occurred (see man page).
Common Grep Mistakes
- Forgetting quotes — the shell may expand
*or spaces before grep runs - Expecting
egrepforever — prefergrep -E - Recursive from
/without excludes — slow and noisy; start from a project path - Treating
-patterns wrong — usegrep -e '--flag' - Binary file noise — add
-Ior--includefor source trees - Assuming
\tworks — 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.

| What you need next | What WPS gives you |
|---|---|
| Turn matched lines into a document or report | Strong .docx / .xlsx / .pptx layout fidelity when files move between Linux, Windows, and macOS |
| One place for notes, sheets, slides, and PDFs | Free core suite: Writer, Spreadsheet, Presentation, plus PDF view/edit/convert tools |
| A familiar desktop UI for switchers | Ribbon-style apps with a lighter footprint than many heavy suites |
| A trusted install path | Official 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.




