Back to Explore
GuideVibeFix editorialUpdated Dec 1, 2026

grep From Zero: The First Lesson in Finding Things in Your Project

grep does one thing: find lines in text that match a pattern. This guide runs every command for real on GNU grep 3.11 — line numbers, case-insensitive search, recursion, context lines, whole-word matching, the three pattern modes (BRE, -E, -F), anchors and alternation, quiet mode for scripts, and binary files — with the output pasted verbatim.

Real photograph of a desk with a monitor showing code, a lamp and a plant (illustrative photo)

People who write code spend every day looking for things in files: how many TODOs are left from last week, which line the ERROR is on, how many files call a given function, what the ops email address in the logs is. There are many tools for finding things, but the first one to learn is always grep: it does exactly one thing — find lines in text that match a pattern — and it does it fast and reliably. The name is its own manual: it comes from the ed editor command g/re/p — global, regular expression, print — turned into a standalone tool by Ken Thompson in 1974. Editors have changed generations since then; grep is still here, because the need to "find lines by pattern" never went away. Every command in this article was run for real on GNU grep 3.11 (bash 5.2.21), and the output is pasted verbatim — type it in and you will get exactly the same result. First, the demo setup: a 13-line notes.txt containing TODOs, a FIXME, an ERROR, an email address, and two similar lines about C++ and C+; a src directory with app.py, server.py, and README.md; and a bin.dat file with binary content. Every example uses these files.

$ cat notes.txt
2026-11-30 deploy: TODO rotate keys before Friday
2026-11-30 login page slow on first load
2026-11-29 FIXME retry loop swallows timeout errors
2026-11-29 catalog search returns stale results
2026-11-28 TODO add rate limit to /api/upload
2026-11-28 ERROR disk full on worker-3, see runbook
2026-11-27 dialog box overlaps the log panel
2026-11-27 contact ops@example.com about the outage
2026-11-26 log rotation moved to 03:00
2026-11-26 the new parser handles C++ code
2026-11-26 the old parser handles C+ code
2026-11-25 todo lowercase reminder: buy coffee
2026-11-25 release notes drafted, no action needed

1. The simplest form: grep pattern file

The basic form is grep pattern file: it reads the file line by line and prints each line that contains the pattern. Finding TODO:

$ grep TODO notes.txt
2026-11-30 deploy: TODO rotate keys before Friday
2026-11-28 TODO add rate limit to /api/upload
exit=0

The key to understanding grep is understanding the words "pattern" and "line". A pattern is a description of what you are looking for: the simplest pattern is literal text, such as TODO; a more complex one is a regular expression, such as 'TODO|FIXME', meaning "TODO or FIXME". grep works as a streaming filter: it reads one line, checks whether the line contains the pattern, prints it if so, discards it if not, and moves on. It never needs to load the whole file into memory, so searching a log file several gigabytes in size will not blow up your RAM; output is streaming too, so matching lines appear as they are found and you can pipe them straight into head to see the first few, or into wc -l to count. You can search several files at once: grep TODO a.txt b.txt c.txt prefixes each line with its source file, so you can see at a glance where every line came from.

The two most-used modifiers are -n and -i. -n prefixes each line with its line number, so you stop counting lines by hand; -i ignores case, catching the lowercase todo as well:

$ grep -n TODO notes.txt
1:2026-11-30 deploy: TODO rotate keys before Friday
5:2026-11-28 TODO add rate limit to /api/upload
exit=0
$ grep -i todo notes.txt
2026-11-30 deploy: TODO rotate keys before Friday
2026-11-28 TODO add rate limit to /api/upload
2026-11-25 todo lowercase reminder: buy coffee
exit=0

-i is worth remembering on its own: TODO, Todo, and todo are spelled inconsistently across a codebase, and searching only the uppercase form misses half of them. -v inverts the match — it prints lines that do not match, which is handy for "filter out the known noise first, then look at what is left":

$ grep -v TODO notes.txt | head -3
2026-11-30 login page slow on first load
2026-11-29 FIXME retry loop swallows timeout errors
2026-11-29 catalog search returns stale results
exit=0

-c counts matching lines instead of printing them. Counting TODO lines:

$ grep -c TODO notes.txt
2
exit=0

Here is the trap beginners hit most often: searching for something that does not exist makes -c print 0, and the exit code is 1, not 0:

$ grep -c ZZZZ notes.txt   (no match: count 0, exit 1)
0
exit=1

grep has three exit codes, and they are worth memorising: 0 means found, 1 means not found, 2 means an error (a missing file, a bad option). Typed by hand in a terminal, exit code 1 looks like just "no output"; inside a script, it decides which branch of an if runs. Section 7 covers -q, which exists precisely for scripts.

How grep works: text files are read line by line, the pattern (fixed string -F, basic regex BRE, extended regex -E) is tested per line, and matching lines are output with -n/-c/-l/-o; exit codes 0 found, 1 not found, 2 error

2. Searching a whole project: -r, --include, -l

Searching one file at a time is too slow. -r makes grep walk into directories recursively, and -n adds the filename and line number:

$ grep -rn TODO src/app.py src/server.py src/README.md
src/app.py:1:# TODO: cache the user profile
src/README.md:2:TODO write the docs
exit=0

Note that server.py does not appear — it contains FIXME, not TODO. grep only honours the pattern, not your intentions: searching for TODO will not also fetch FIXME. To search for both, use -E 'TODO|FIXME', covered in section 6.

Once a project grows, recursive search will also churn through build output, dependency directories, and .git. Use --include to search only one kind of file:

$ grep -rn --include='*.py' TODO src
src/app.py:1:# TODO: cache the user profile
exit=0

README.md is excluded, leaving a single line from app.py. The mirror options are --exclude and --exclude-dir; --exclude-dir=.git skips the repository directory, and both are used almost daily in real projects. The combination you will actually type most often is something like grep -rn --include='*.py' --exclude-dir={.git,node_modules,__pycache__} TODO . — only Python files, skipping the version-control directory, the dependency directory, and the cache directory. If you do not skip the dependency directory, one recursive search can dredge up tens of thousands of lines of third-party TODOs, which is not your job. ripgrep (rg) skips these directories by default, which is one reason people switch to it; but grep with these options does the same thing.

Sometimes you do not care about the matching lines, only about which files contain them. -l prints just the filenames:

$ grep -rl TODO src/app.py src/server.py src/README.md
src/app.py
src/README.md
exit=0

That output can be fed straight into another command, for example grep -rl TODO src | xargs sed -i 's/TODO/DONE/' for a bulk rewrite — though you should back up before any bulk rewrite, which is another topic.

3. Seeing context, printing only the match: -B, -A, -o

Finding the ERROR line is rarely enough; you usually need to see what happened around it. -B (before) shows the preceding lines, -A (after) the following lines, and -C (context) both sides:

$ grep -B1 -A2 ERROR notes.txt
2026-11-28 TODO add rate limit to /api/upload
2026-11-28 ERROR disk full on worker-3, see runbook
2026-11-27 dialog box overlaps the log panel
2026-11-27 contact ops@example.com about the outage
exit=0

The line before the ERROR is a TODO (rate-limiting the upload endpoint that day); the two lines after are a dialog-box problem and the ops email. When reading logs, -C 3 is close to standard: a lone error line on its own usually tells you nothing. -C is the combination of -B and -A: grep -C 3 ERROR notes.txt shows three lines on each side. A practical workflow for production logs is to count the errors first with -c, then use -C 5 on the first and last occurrences — the first usually shows how the problem started, the last shows where it has got to. If a key detail appears in the context (like the ops email above), use it as the pattern for the next grep and follow the trail. Context lines and matching lines are separated by -- by default, unless the matches are adjacent, in which case the separator does not appear.

-o prints only the matched fragment, not the whole line. Combined with extended regex -E, it can pull email addresses out of a log one by one:

$ grep -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' notes.txt
ops@example.com
exit=0

The regex reads: before the @, a run of letters, digits, dots, underscores, percent signs, plus signs, and hyphens; after it, a domain; then a top-level domain of at least two letters. It is not a perfect email validator — the real rules are far more complicated — but for fishing addresses out of logs it is good enough. Another common use of -o is counting how many times a word occurs: grep -o 'TODO' notes.txt | wc -l, because -c counts lines, and a line containing TODO twice still counts as one, while -o prints both occurrences.

4. Whole-word matching: -w, for when one word drags in a crowd

By default grep does substring matching: any line containing the pattern counts. That is often a strength, but it also creates noise. Searching for log:

$ grep log notes.txt   (substring: login and catalog match too)
2026-11-30 login page slow on first load
2026-11-29 catalog search returns stale results
2026-11-27 dialog box overlaps the log panel
2026-11-26 log rotation moved to 03:00
exit=0

Two of the four lines are false positives: login contains log, and so does catalog. To match the word log itself, add -w:

$ grep -w log notes.txt   (whole word only)
2026-11-27 dialog box overlaps the log panel
2026-11-26 log rotation moved to 03:00
exit=0

Only two lines remain. -w judges by word boundaries: the match must not be flanked by a letter, digit, or underscore. So log matches the log in "the log panel", but not the log inside login or catalog. When searching for function names, variable names, or config keys, -w saves a lot of manual filtering. Conversely, if you genuinely want substrings (every word containing log), leave -w off — the default is what you want.

-w is often stacked with other options: grep -rniw 'error' . searches recursively, case-insensitively, for the word error itself — in a project of thousands of files, that one command cuts false positives to a minimum. One detail worth remembering: the underscore counts as a word character, so grep -w 'log' will not match the log inside error_log; if you want those too, skip -w and use the regex word-boundary idea \blog\b instead, or widen the pattern and filter by hand afterwards. The options are fixed; the judgement is yours: first decide whether you want "this word" or "everything containing this word", then decide whether to add -w.

5. Three pattern modes: default, -E, -F — one C++ example explains them all

grep really has three "languages", and picking the wrong one gives surprising results. The default is basic regular expressions (BRE), -E is extended regular expressions (ERE), and -F is fixed strings (no regex interpretation at all). notes.txt has two lines that look alike:

2026-11-26 the new parser handles C++ code
2026-11-26 the old parser handles C+ code

Searching for C++ with -F treats the plus signs as plus signs, matching only the first line:

$ grep -F "C++" notes.txt   (fixed string)
2026-11-26 the new parser handles C++ code
exit=0

Searching for C++ with -E turns the plus into a quantifier ("one or more C"), matching both lines:

$ grep -E 'C++' notes.txt   (ERE: + is a quantifier, so C+ matches too)
2026-11-26 the new parser handles C++ code
2026-11-26 the old parser handles C+ code
exit=0

In default BRE, the plus is an ordinary character, so plain grep 'C++' (without -E) behaves like -F and matches only the first line. This detail is the source of a lot of beginner confusion: the same pattern gives different results under a different option. The rule of thumb: when searching for a fixed string (such as C++, 192.168.1.1, or foo.bar), prefer -F so regex symbols never get a chance to interfere; when you need regex power such as |, +, ?, or {}, use -E; default BRE is only needed for old-style spellings like \( and \+, which you can mostly avoid day to day.

By the way, . in a regex means "any single character", so grep '192.168.1.1' would also match something like 192x168y1z1 — another case where -F is the right choice for IP addresses and domain names.

6. Regex basics: anchors, alternation, character classes

Once you know -E, three regex building blocks multiply what grep can express: anchors, alternation, and character classes. Anchors first. ^ means "start of line" and $ means "end of line". To see only the records from 30 November:

$ grep '^2026-11-30' notes.txt   (anchor: lines starting with this date)
2026-11-30 deploy: TODO rotate keys before Friday
2026-11-30 login page slow on first load
exit=0

^2026-11-30 matches only lines beginning with that date; a line with the date in the middle would not match. Now the end anchor, for lines ending in needed:

$ grep 'needed$' notes.txt   (anchor: lines ending with 'needed')
2026-11-25 release notes drafted, no action needed
exit=0

Only one line ends with needed. The most common uses of anchors are searching for lines whose content is already known, such as grep '^import ' *.py for all import statements, or grep 'TODO$' *.md for TODOs still hanging at the end of a line. Note that $ is special to the shell (variable expansion), so the pattern must be wrapped in single quotes — a rule that applies to every pattern containing $, *, or ?.

The second building block is alternation, written with | (needs -E). Section 2 left a loose end: searching for TODO does not also fetch FIXME. To get both, use alternation:

$ grep -E 'TODO|FIXME' notes.txt   (ERE alternation: either word)
2026-11-30 deploy: TODO rotate keys before Friday
2026-11-29 FIXME retry loop swallows timeout errors
2026-11-28 TODO add rate limit to /api/upload
exit=0

Three lines, none missing. Alternation stacks: grep -E 'TODO|FIXME|XXX|HACK' . -r is the classic pre-release sweep for leftover markers. The third block is the character class [...], meaning "any one of the characters inside the brackets". To find all records from 28 and 29 November:

$ grep -E '2026-11-2[89]' notes.txt   (character class: 28th or 29th)
2026-11-29 FIXME retry loop swallows timeout errors
2026-11-29 catalog search returns stale results
2026-11-28 TODO add rate limit to /api/upload
2026-11-28 ERROR disk full on worker-3, see runbook
exit=0

2[89] matches 28 or 29, and all four lines are from those two days. Classes can also hold ranges: [0-9] is any digit, [a-z] is any lowercase letter, and [^0-9] is any non-digit (the ^ inside brackets means negation). These three blocks, plus . (any single character) and * (zero or more of the previous element), already cover about eighty percent of everyday regex needs. More advanced regex — groups, quantifiers, greedy versus non-greedy matching — can wait until you actually meet them; getting fluent with these three first gives the biggest return.

7. Using grep in scripts: -q and exit codes

The most common form of grep inside a script is -q: quiet mode, which returns 0 when it finds something and prints nothing. Checking whether the file contains a FIXME:

$ grep -q FIXME notes.txt
exit=0
$ grep -q ZZZZ notes.txt; echo exit=$?
exit=1

The first command found something, exit code 0; the second found nothing, exit code 1. In a script that reads:

if grep -q FIXME notes.txt; then
  echo "FIXME still open, don't ship yet"
fi

That is where the three exit codes from section 1 earn their keep: 0 found, 1 not found, 2 error. The third code, 2, means an error: a missing file or a bad option, with grep writing the error to standard error (stderr) and returning 2. Scripts need to tell 1 and 2 apart: 1 means "searched properly, nothing there", 2 means "could not search at all". A robust script checks that the file exists before searching, or checks after searching whether the exit code is 2 — 2 means the command itself failed, not that nothing was found. Typed by hand, 2 is easy to recognise: the terminal prints an error line directly, such as grep: no-such-file.txt: No such file or directory, and never passes quietly.

One trap deserves a warning: grep -q combined with set -e will make a script exit immediately on "not found", because set -e treats any non-zero exit code as failure. If your script starts with set -e, put the test inside an if (a non-zero exit code in an if condition does not trigger set -e); do not leave a bare grep -q standing in the middle of a command sequence.

8. Binary files: grep gives you a one-line verdict

When grep meets a binary file, it does not dump garbage into your terminal; it gives a one-line verdict instead:

$ grep TODO bin.dat   (binary file: only a one-line verdict)
grep: bin.dat: binary file matches
exit=0

bin.dat was made deliberately: AB, a NUL byte, TODO, a NUL byte, CD. grep tells you "this file contains a match" without printing its contents — that protects your terminal from binary garbage. Note the exit code is still 0, because something was found.

If you really want to see the text inside a binary file, add -a to treat it as text, and pair it with -o to print only the matched fragment:

$ grep -a -o TODO bin.dat   (-a treats it as text, -o prints only the match)
TODO
exit=0

Going the other way, if you never want grep to touch binary files, the GNU grep manual offers -I (capital i): binary files are treated as having no match and skipped outright. When searching a whole project recursively, grep -rI is a very practical combination — it skips compiled executables and images and searches only real text.

9. Scope: grep is not a universal tool, and this site already covers its neighbours

grep is good at "finding lines by pattern in a pile of text". Beyond that range, switch tools: structured data (JSON, CSV) needs a parser, not a regex — a comma inside quotes breaks any column-splitting logic, as the cut guide in this same cycle demonstrates live; multi-line patterns and cross-line matching are not grep's strength; when you need arithmetic or grouped statistics by field, that is awk's job (this site already has an awk guide).

As for this site's existing guides: the ripgrep guide covers rg, the faster replacement that recurses by default and honours .gitignore, best for daily code search; the shell pipes guide covers how | chains commands together; the text-processing overview mentions grep in a single sentence ("grep finds, sed edits, awk computes on logs") — this article is the full deep dive on grep, not a repeat of that overview; sed and awk each have their own guides, and this article does not cover replacing or computing by column, only "finding".

When should you move from grep to rg? Three rules of thumb: first, when the project is very large and the file count very high, rg's parallel search and default ignore rules are much faster; second, when you search code every day and often jump straight from the result into an editor to fix it, rg's output format and editor integration feel smoother; third, when the thing you are searching for lives under .gitignore (and you do not want to search node_modules), rg skips it by default while grep needs a manual --exclude-dir. In the other direction, grep's advantage is that it is everywhere: it exists on any Linux or macOS machine, so scripts, CI pipelines, and container troubleshooting never need to install anything first. Learn grep properly first, then pick up rg — you will understand much better exactly what rg is saving you.

10. Common mistakes

Finally, three traps beginners hit most often. First, searching a directory without -r: grep TODO src fails with grep: src: Is a directory, because grep only reads files by default and a directory needs -r to enter. Second, an unquoted * in the pattern: in grep *.py notes.txt, the shell expands *.py into the filenames in the current directory before grep ever sees it, so grep receives something entirely different from the pattern you meant — always wrap patterns in single quotes, with no exceptions. Third, using LC_ALL=C on Chinese text: this article's demo sets LC_ALL=C deliberately so the output is byte-stable, but in real life searching Chinese text under LC_ALL=C makes grep understand the text byte by byte instead of character by character, so . can match half a Chinese character and multi-byte boundaries can break. Before searching Chinese, switch the variable to LC_ALL=C.UTF-8 or simply unset it and let the system use its default UTF-8 locale.

11. Cheat sheet and exercises

grep PATTERN FILE          find lines containing the pattern
grep -n PATTERN FILE       with line numbers
grep -i PATTERN FILE       ignore case
grep -v PATTERN FILE       invert (lines without the pattern)
grep -c PATTERN FILE       count lines only (exit code 1 when 0 lines)
grep -r PATTERN DIR        search a directory recursively
grep -rn --include='*.py' PATTERN DIR   only one file type
grep -rl PATTERN DIR       list filenames only
grep -B2 -A2 PATTERN FILE  two lines of context on each side
grep -o PATTERN FILE       print only the matched part
grep -w PATTERN FILE       whole-word match
grep -F 'C++' FILE         fixed string (no regex interpretation)
grep -E 'a|b' FILE         extended regex (alternation, plus, etc.)
grep -q PATTERN FILE       quiet test (for scripts)
grep -rI PATTERN DIR       recurse, skipping binary files

Practice: run these three commands in your own project and see whether the results match what you expect: grep -rn --include='*.py' TODO . (how many TODOs are left in your project), grep -rn -i 'fixme\|xxx\|hack' . (the temporary workarounds left behind over the years), and grep -rI 'password\|secret\|api_key' . (anything that should never have entered the repository — if you find a hit, do not panic: check whether it is a fake value for tests first, then decide what to do). After those three, you will know your project better than you did a minute ago.

Two more advanced exercises. First, log investigation: take a real log you have on hand (say a development server's access.log), count the 500 errors with grep -c ' 500 ' access.log, then look at what happened around the first 500 with grep -B2 -A2 ' 500 ' access.log | head -40 — note the spaces around 500, added deliberately so that 5000 or 1500 are not caught too; that is the whole-word idea from section 4 in a different form. Second, build yourself a small "project health check" script: put the three commands above into a shell script, run it weekly, redirect the output to a file, and compare the TODO count every few weeks to see whether it is rising or falling. Teams that steadily push their TODO count down rarely have terrible code quality. The cut guide in the next round covers the other half: once you have found the lines, how to slice the fields out of them.

Views 1Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photograph of a wooden desk with a white alarm clock beside a calendar page (illustrative photo)
Guide
crontab From Zero: Jobs That Just Run on Time, Five Fields Explained Once

cron is the scheduling daemon that has run on Linux for decades: write a crontab file saying 'run this command at this time', and it handles the rest. This guide runs everything for real on Debian cron 3.0pl1-162 — installing a job, waiting one minute for the trigger, verifying the log, removing the job — plus special strings, five classic mistakes, and a real 3 a.m. log-archiving job.

Developer WorkflowAutomationTool Tips
Real photograph of a server room patch panel filled with blue network cables (illustrative photo)
Guide
ping From Zero: One Packet Tells You If It Is Alive — the Exit Code Matters More Than the Output

ping does exactly one thing: send an ICMP echo request, wait for the echo reply, and report the round-trip time and packet loss. This guide runs every command for real on iputils ping 20240117 — packet count, interval, quiet mode, packet size, timestamps, IPv4 vs IPv6, the three failure modes, exit codes 0/1/2 — with output pasted verbatim.

Developer WorkflowTool TipsDebugging
Real photograph of scissors cutting a white sheet of paper on a white background (illustrative photo)
Guide
cut From Zero: Slicing Columns Out of Lines

cut does one thing: split each line into fields on a delimiter and output the fields you ask for. This guide runs every command for real on GNU coreutils 9.4 — field lists and ranges, CSV and output delimiters, character slicing, --complement, the -s rule for lines without a delimiter, log-column statistics, and the quoted-comma limit — with the output pasted verbatim.

Developer WorkflowTool TipsAI Coding