Searching with grep
Filter lines with grep: count, invert, ignore case, print only matches, search trees, and read exit statuses. macOS BSD grep has no -P.
Searching with grep
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- grep PATTERN FILE prints the lines that match. With no file it reads stdin, so it fits at any point in a pipeline.
- Common flags: -i ignore case, -v invert, -c count lines, -n line numbers, -o only the matching part, -l file names only, -r recurse, -w whole words, -F fixed string.
- The pattern is a regular expression. Plain grep uses basic syntax, and -E switches to extended so (a|b) and + work without backslashes.
- Exit status is 0 if a line matched, 1 if none did, and 2 on error. That makes grep -q a clean test in an if statement.
- Quote the pattern so the shell leaves it alone. macOS grep is BSD: there is no -P and no \d, so use -E with [0-9].
Finding the lines that matter
A log has 200 lines today and 2 million next month. You can’t read it. What you want is to say “show me only the lines that look like this”, and then pipe those on. grep does that. The name comes, as I remember it, from an old editor command, g/re/p: globally search for a regular expression and print. It reads lines, keeps the ones that match, and discards the rest.
My data is the 200-line web-server log from the fixture. The status code is the eighth space-separated field, so a space on both sides of a code is a good pattern:
$ grep ' 404 ' logs/access.log | head -3
198.51.100.4 - - [2026-11-02T13:49:00Z] "GET / HTTP/1.1" 404 5281
10.0.0.5 - - [2026-11-03T21:33:00Z] "GET /static/app.js HTTP/1.1" 404 8457
198.51.100.4 - - [2026-11-04T14:14:00Z] "GET /admin HTTP/1.1" 404 6206
Spaces matter. Searching bare 404 could also hit a byte count like 5404. Always quote the pattern, as you’ll see below why.
The flags you will actually use
-ccounts matching lines instead of printing them.-vinverts: lines that do not match.-iignores case.-nprefixes line numbers.-oprints only the matched part.-lprints names of files containing a match.-hhides the file name prefix.-rsearches a directory tree.-wmatches whole words only.-xmatches the whole line.-Ftreats the pattern as a fixed string, not a regex.
I tried them on the log and on two small markdown files with TODO in various cases:
$ grep -c ' 404 ' logs/access.log
16
$ grep -vc ' 200 ' logs/access.log
96
$ grep -i todo docs/a.md
TODO: fix login
Todo lower
$ grep todo docs/a.md
$ grep -ci todo docs/*.md
docs/a.md:2
docs/b.md:1
With no -i, todo matched nothing in a.md, which has TODO and Todo. Given more than one file, grep prefixes each line (or count) with the file name.
To pull just the address out of each line, use -o:
$ grep -o '10\.0\.0\.[0-9]*' logs/access.log | sort | uniq -c
40 10.0.0.5
40 10.0.0.7
The dots are escaped because an unescaped . in a regex matches any character. Add -F if you’d rather skip regexes: printf 'a.c\nabc\n' | grep 'a.c' printed both lines, while grep -F 'a.c' printed only the first.
Regex dialects: basic and extended
grep patterns come in two common flavours. The default is basic (BRE), where +, ?, | and () are plain characters unless escaped. -E selects extended (ERE), where they are operators:
$ grep -E ' (404|500) ' logs/access.log | wc -l
40
$ grep ' \(404\|500\) ' logs/access.log | wc -l
40
Same answer, different spelling. I find ERE easier to read. Anchors work in both: ^10\. counted 80 lines starting with 10., and '200$' found nothing because every line ends with a byte count and not a status. Character classes such as [0-9] and [[:digit:]] are portable.
What differs on macOS
macOS ships BSD grep (here 2.6.0-FreeBSD). Habits from Linux tutorials fail in two places:
$ grep -P '\d+' docs/a.md
grep: invalid option -- P
$ echo 'abc 123' | grep -o '\d+'
$ echo 'abc 123' | grep -oE '[0-9]+'
123
-P (Perl regexes) doesn’t exist, and \d silently matches nothing. Use -E with [0-9]. BSD grep did accept a\+ in basic mode in my test (it matched aaa), as GNU does, but that is a GNU extension to POSIX, so don’t depend on it in a portable script. I didn’t run GNU grep.
Exit status makes it a test
grep returns a status you can branch on:
$ grep -q ' 404 ' logs/access.log; echo "found=$?"
found=0
$ grep -q 'NOPE' logs/access.log; echo "notfound=$?"
notfound=1
$ grep 'x' missing.txt; echo "error=$?"
grep: missing.txt: No such file or directory
error=2
-q prints nothing and exits at the first match. In a script, if grep -q pattern file; then ... works. Note that 1 (“no match”) isn’t an error. And -s silences the missing-file message but the status stays 2.
Searching trees and showing context
$ grep -rn -i 'todo' docs --include='*.md' | sort
docs/a.md:1:TODO: fix login
docs/a.md:3:Todo lower
docs/b.md:2:todo: later
$ grep -n -B1 -A1 'ok line' docs/a.md
1-TODO: fix login
2:ok line
3-Todo lower
-r walks directories (and --include or --exclude-dir narrow it), and -B and -A add lines Before and After a match, with - marking context lines and : marking real matches. A file with a NUL byte printed Binary file bin.dat matches, and -a forced text.
Quote the pattern
With x1 and x2 files present, echo x | grep x* printed nothing: the shell turned x* into x1 x2, so grep searched for x1 inside the file x2. grep 'x*' kept the pattern intact. This is the same lesson as globbing: characters like *, ? and [ mean something to the shell first. If the pattern starts with a dash, use -e or --: printf -- '-v is an option\n' | grep -- '-v' worked.
About the video
Corey Schafer’s “Linux/Mac Terminal Tutorial: The Grep Command - Search Files and Directories for Patterns of Text” was published 7 March 2018 and runs 20 minutes 16 seconds. The description says it covers searching files and directories and piping other commands into grep. It has no chapters, and I couldn’t read a transcript, so I can’t tell you which flags it demonstrates or how it handles regex flavours. It is explicitly aimed at Mac as well as Linux, which is why I picked it over Linux-only videos; it is the oldest pick in this part of the roadmap, and grep itself hasn’t changed. English per its title and description. Learn Linux TV’s 15-minute video is the alternative.
What I did not run
GNU grep, -P, egrep and fgrep, ripgrep, and the -z null-data mode.
Next
grep selects lines. The next lesson reshapes what is left, with sort, uniq, cut, tr and wc: sort, uniq, cut, tr and wc.
Check yourself
You want the number of requests with status 404 in a log. Which flag, and why might wc -l give the same number?
grep -c ' 404 ' file counts matching lines. grep ... | wc -l counts the same lines, since grep prints one line per match. -c just avoids the extra process.
What do grep's exit codes 0, 1 and 2 mean?
0 means at least one line matched, 1 means the search ran and found nothing, and 2 means an error such as a missing file. Scripts should treat 1 differently from 2.
You run echo x | grep x* and nothing happens. Why?
The shell expands x* against files in the current directory before grep starts, so grep receives different arguments. Quote it: grep 'x*'.
How do you print only the IP-address part of each matching line instead of the whole line?
grep -o with a pattern for the address, for example grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' file. -o prints only the matched text, one match per line.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.