Cheat Sheets

Grep Cheat Sheet: GNU grep Options, Regex and ripgrep Examples

grep -c doesn’t count matches. It counts lines that contain a match, so a log line that says ERROR twice adds one to the total, and an alert built on that number undercounts every time a message repeats the word. Most of what people get wrong about grep works the same way: the flag does something narrower or wider than its name suggests, and the output looks plausible enough that nobody checks.

Original content from computingforgeeks.com - post 185690

This grep cheat sheet starts with the quick-reference tables, then proves each group of GNU grep options against a small lab dataset. You get case and word matching, basic versus extended versus Perl regex, counting, context lines, recursive search filters, and -z for data that isn’t one record per line. Each section ends with the ripgrep (rg) equivalent and the default where rg disagrees with grep. Everything below was run on Ubuntu 26.04 with GNU grep 3.12 and ripgrep 15.1.0 in November 2026, and the places where Fedora 45 behaves differently were checked on a second VM.

grep cheat sheet: the quick reference

Use these tables when you know the job and need the flag. Every row ran in the lab, and the sections further down show the output, the edge case and the ripgrep form for each group. Quote the pattern in single or double quotes every time, because an unquoted *, | or { gets rewritten by your shell before grep ever sees it. When the lookup you need is a command’s own examples rather than a regex, the tldr command examples guide shows how to install the tldr client and keep its example pages current.

Match and filter lines

CommandWhat it does
grep ERROR app.logPrint lines containing ERROR (case-sensitive)
grep -i error app.logIgnore case
grep -v INFO app.logInvert: lines that do not match
grep -n WARN app.logPrefix each line with its line number
grep -w error app.logWhole word only (underscore counts as a letter)
grep -x "server {" nginx.confWhole line must match
grep -F "10.0.1.5" app.logFixed string, dots are literal
grep -e ERROR -e WARN app.logSeveral patterns, any one matches
grep -f patterns.txt app.logRead patterns from a file, one per line
grep -v -e "^\s*#" -e "^\s*$" nginx.confStrip comments and blank lines

Regex flavours: BRE, ERE and PCRE

CommandWhat it does
grep "ERROR\|WARN" app.logAlternation in basic regex (GNU extension)
grep -E "ERROR|WARN" app.logAlternation in extended regex
grep -E "[0-9]{4}ms" app.logInterval without backslashes
grep "[0-9]\{4\}ms" app.logSame interval in basic regex
grep -P "\d{4}ms" app.log\d and other Perl classes need -P
grep -oP "(?<=user=)\w+" app.logLookbehind: print only the value after user=
grep -oP "took \K\d+" app.log\K drops everything matched before it

Output, counting and exit codes

CommandWhat it does
grep -oE "[0-9]+ms" app.logPrint only the matched text, one per line
grep -c ERROR app.logCount matching lines
grep -o ERROR app.log | wc -lCount matches
grep -rl ERROR logs/List files that match
grep -rL ERROR logs/ conf/List files that do not match
grep -m 1 ERROR app.logStop after the first matching line
grep -q ERROR app.logNo output, exit 0 found, 1 not found, 2 error
grep -H ERROR app.logAlways print the file name
grep -rh ERROR logs/Never print the file name

Context lines

CommandWhat it does
grep -A 4 "exception" app.logMatch plus 4 lines after
grep -B 2 "ZeroDivisionError" app.logMatch plus 2 lines before
grep -C 1 "ERROR db" app.log1 line either side
grep -A 1 --no-group-separator "user=deploy" app.logDrop the -- line between groups
grep -A 1 --group-separator="===" "user=deploy" app.logUse your own separator

Recursive search and file filters

CommandWhat it does
grep -r TODO webapp/Search a tree, skip symlinks found inside it
grep -R TODO webapp/Search a tree and follow every symlink
grep -rn --include="*.py" TODO .Only files whose name matches the glob
grep -r --include="*.py" --include="*.js" TODO .Two globs need two flags (no braces)
grep -r --exclude="*.min.js" TODO .Skip files by name
grep -r --exclude-dir=node_modules TODO .Skip a directory by name
grep -r --exclude-dir=".*" TODO webapp/Skip hidden directories such as .git (never with a . path)
grep -rI TODO .Skip binary files
grep -a TODO logo.binTreat a binary file as text

Multiline and NUL-separated data

CommandWhat it does
grep -zoP "(?s)location /api \{.*?\}" nginx.confMatch across newlines (output ends in NUL)
grep -rlZ TODO src/ | xargs -0 wc -lNUL-terminated file names for xargs -0
find src -name "*.txt" -print0 | xargs -0 grep -H TODOFeed grep names with spaces safely
printf "a\0TODO b\0c TODO\0" | grep -zc TODOCount NUL-separated records

ripgrep equivalents

CommandWhat it does
rg TODO .Recursive by default, skips gitignored, hidden and binary files
rg -u TODO .Also search gitignored files
rg -uu TODO .Also search hidden files
rg -uuu TODO .Also search binary files (grep -r scope)
rg -L TODO .Follow symlinks (like grep -R)
rg -t py TODO .Only one file type (rg –type-list)
rg -g "!*.min.js" TODO .Glob filter, ! excludes
rg -c ERROR app.logCount matching lines (grep -c)
rg --count-matches ERROR app.logCount matches (grep -o | wc -l)
rg -o "\d{4}ms" app.log\d works without -P
rg -oP "(?<=user=)\w+" app.logLookaround needs -P (PCRE2)
rg -U "location /api \{[^}]*\}" nginx.confMultiline match (grep -z)
rg -o 'user=(\w+)' -r '$1' app.logPrint a capture group

If you only need one fact from these tables, take this one: grep searches what you point it at, while rg searches what your .gitignore lets it see. The rest of this page is the evidence for that and for every other row above, starting with how grep decides that a line matches.

grep matches lines, not words

grep tests each line against the pattern and prints the whole line when any part of it matches. That’s why grep error prints error_count=0 for you: the five letters sit inside a longer token, and grep has no idea what a token is unless you ask. The lab works from ~/grep-lab, which holds an application log, an nginx access log, an nginx config and a small git project. Every app-log example on this page runs against these 14 lines, shown here with cat -n so you can check each count yourself:

     1	2026-11-08 09:14:02 INFO  api started on :8080 user=deploy
     2	2026-11-08 09:14:05 INFO  cache warmed in 412ms
     3	2026-11-08 09:15:11 WARN  slow query took 1840ms user=reports
     4	2026-11-08 09:15:12 ERROR db timeout after 3000ms user=reports
     5	2026-11-08 09:16:40 INFO  error_count=0 since restart
     6	2026-11-08 09:17:03 ERROR upstream refused, ERROR budget at 80%
     7	2026-11-08 09:17:04 INFO  error-rate below threshold
     8	2026-11-08 09:18:22 ERROR unhandled exception in worker
     9	Traceback (most recent call last):
    10	  File "/srv/app/worker.py", line 41, in run
    11	    job.execute()
    12	ZeroDivisionError: division by zero
    13	2026-11-08 09:18:30 INFO  worker restarted user=deploy
    14	2026-11-08 09:19:00 INFO  order_id=10203145 processed in 95ms

Case comes first. grep ERROR is case-sensitive and returned three lines, while grep -i error returned six, including the ZeroDivisionError line from the traceback, because -i folds case across the whole line. What happens when you add -w to a lowercase search?

grep -w error logs/app.log

One line survives, and it’s the hyphenated one:

2026-11-08 09:17:04 INFO  error-rate below threshold

-w requires the match to sit between non-word characters, and GNU grep counts letters, digits and the underscore as word characters. So error_count is one word and gets skipped, while error-rate is two words joined by a hyphen and gets printed. If you’re hunting a variable name in code, -w does what you want. If you’re hunting a word in prose that uses hyphens, it’ll surprise you. -x goes further and demands the whole line: grep -c server counted 3 lines in the nginx config, while grep -xc "server {" counted only the block opener, skipping the server_name line and the comment.

The dot is the other trap. In a pattern, . means any character, so when you search for an IP address you’re really searching for a shape. The app log has no IP in it, yet grep "10.0.1.5" printed the order_id=10203145 line. Those eight digits fit the pattern, with the 2, the 3 and the 4 standing in for the three dots.

grep -F treats the pattern as a fixed string and returned nothing with exit status 1, which is the correct answer. Even -F is not enough on the access log, though, as you can see when you count:

grep -w skips error_count but matches error-rate, and grep -F 10.0.1.5 also matches 10.0.1.50 until -w is added, on Ubuntu 26.04

grep -F -c "10.0.1.5" counted 4 lines, but only 3 requests came from 10.0.1.5. The fourth is 10.0.1.50, which contains the string. -Fw brings the count down to 3, because the trailing 0 is a word character and breaks the word boundary. For IP addresses, the safe form is the combination:

  • -F so the dots are literal
  • -w so longer addresses such as 10.0.1.50 drop out
  • -c or -o only after the first two are right

You can pass several patterns with repeated -e flags, or put them in a file for -f, one pattern per line. Both lab runs printed the same four WARN and ERROR lines. -e also matters when a pattern starts with a dash, since grep -e "-v" file searches for the text -v instead of inverting the match. Stripping comments and blank lines from a config is the everyday use of two -e patterns with -v:

grep -v -e "^\s*#" -e "^\s*$" conf/nginx.conf

The 18-line nginx config came back as 13 lines of directives, with the comment lines and the blank lines gone:

user  nginx;
worker_processes  auto;
server {
    listen 80;
    server_name example.com;
    location /api {
        proxy_pass http://127.0.0.1:8080;
        proxy_read_timeout 30s;
    }
    location /static {
        root /srv/www;
    }
}

The \s* in both patterns catches indented comments too, which a plain ^# would leave behind. When you inherit a long default config, that one line is the fastest way to see what it actually sets.

Basic regex treats the pipe as a literal

GNU grep ships three regex engines, and the one you get without a flag is the oldest. In basic regex (BRE), |, +, ?, { and ( are ordinary characters until you put a backslash in front of them. Extended regex (-E) flips that, and Perl-compatible regex (-P, built on PCRE2) adds the classes and lookarounds you know from other languages. In order of what each one gives you:

  1. BRE (default): \|, \{4\}, \(group\)
  2. ERE (-E): |, {4}, (group), +, ?
  3. PCRE (-P): \d, \w, lookbehind, \K, lazy .*?

The capture below runs the same alternation three ways. grep "ERROR|WARN" printed nothing and exited 1, because BRE looked for the literal ten characters ERROR|WARN. The backslash form and -E both returned the same four lines:

grep "ERROR|WARN" returns nothing in basic regex while the backslash form and grep -E match, and \d only works with -P on GNU grep 3.12

The \d line is the one that costs people time. Without -P, grep 3.12 on Ubuntu treated \d as a plain d, printed no warning, and exited 1. A one-line test makes it obvious:

echo "build d1" | grep -o "\d"

Both letters d came back and the digit didn’t:

d
d

Use [0-9] in BRE and ERE, and keep \d for -P. The GNU grep release notes say stray backslashes have triggered a warning since 3.8 and may become errors later. Ubuntu stays silent only because its Debian-derived package patches that warning off. Set DEB_GREP_ENABLE_STRAY_BACKSLASH_WARN=1 and the Ubuntu build printed grep: warning: stray \ before d, which is exactly what Fedora 45 printed with no variable set. A script that depends on \d quietly meaning d is already living on borrowed time.

PCRE earns its place when you want part of a line rather than the whole line. A lookbehind prints the value after a key without the key itself, and \K does the same job with less typing:

grep -oP "took \K\d+" logs/app.log

Only the number from the slow-query line is printed, ready to feed into sort -n or a threshold check:

1840

egrep and fgrep still exist on Ubuntu 26.04 and ran without a message, but upstream has deprecated them since 2007, and since grep 3.8 they print an obsolescence warning on builds that do not patch it out. Write grep -E and grep -F in anything you’ll run on more than one distro.

Fedora 45 ships the same grep 3.12 without those patches, so the identical commands produce extra lines on stderr. The results on stdout don’t change, but a cron job that mails any stderr output will start sending warnings the day you move it to Fedora:

Fedora 45 with GNU grep 3.12 printing the stray backslash warning for \d and the egrep and fgrep obsolescence warnings, plus ripgrep 15.2.0

Side by side, the two lab VMs differ in the places below. Everything Fedora re-ran matched Ubuntu exactly: -c against -o | wc -l (3 and 4), the -w result, the quoted brace --include exiting 1, the four rg filter layers (4, 6, 8 and 9 files) and the rg stdin trap.

BehaviourUbuntu 26.04Fedora 45
GNU grep version3.123.12
grep "\d" stray backslash warningSilent (Debian patch)grep: warning: stray \ before d
egrep / fgrepSilent (Debian patch)egrep: warning: egrep is obsolescent; using grep -E
ripgrep package15.1.0 (apt install ripgrep)15.2.0 (dnf install ripgrep)

grep: Unmatched ( or \(

This error means an ERE pattern opened a group it never closed. grep -E "(timeout" logs/app.log printed exactly that message and exited with status 2, which scripts must treat as “grep failed”, not “no match”. The same mistake under -P reads differently, grep: missing closing parenthesis, with the same exit status 2. Escape the parenthesis ("\(timeout"), switch to -F for a literal search, or drop -E so BRE reads the bare ( as text.

grep -c counts lines, -o counts matches

The sixth log line says ERROR twice, which makes it the test case for every counting flag. grep -c ERROR printed 3. Piping grep -o ERROR into wc -l printed 4, because -o emits each match on its own line. ripgrep keeps the same split: rg -c counts lines and rg --count-matches counts matches.

grep -c ERROR prints 3 while grep -o ERROR piped to wc -l prints 4, and rg -c vs rg --count-matches show the same split

Which one do you want? For “how many requests failed”, lines are usually right, since one request writes one line. For “how many times did this token appear”, you want matches.

-o also works as an extractor on its own. Run grep -oE "[0-9]+ms" on the app log and you get every duration it recorded, from 95ms to 3000ms. The same idea counts requests per client IP in the access log:

grep -oE "^[0-9.]+" logs/access.log | sort | uniq -c | sort -rn

The busiest client sits on top, and it’s the one that hit /api/login twice with a 401:

      3 10.0.1.5
      2 10.0.1.22
      1 10.0.1.50
      1 10.0.1.31

For file lists, -l prints names that match and -L prints names that don’t. grep -rL ERROR logs/ conf/ returned the two files with no ERROR line, logs/access.log and conf/nginx.conf. -m 1 stops reading a file at the first match. On a multi-gigabyte log, that saves you real time when you only need to know where the trouble started.

Scripts should branch on the exit status, not on output. -q prints nothing, and the lab run showed all three codes in one go:

grep -q ERROR logs/app.log; echo "found: $?"; grep -q FATAL logs/app.log; echo "missing: $?"; grep -q ERROR nope.log; echo "error: $?"

A match exits 0, no match exits 1, and a missing file exits 2 with a message on stderr:

found: 0
missing: 1
grep: nope.log: No such file or directory
error: 2

Adding -s hides that message but still exits 2, so if grep -qs ... treats a missing log the same as a clean one. That is fine for an optional file and wrong for a health check. The exit codes split three ways:

  • 0: at least one line matched
  • 1: no line matched, nothing went wrong
  • 2: an error, such as a missing file or a bad pattern

The codes are not exclusive. A recursive search that matches files but hits one unreadable file still exits 2, as the timing runs at the end of this page show, while -q exits 0 on a match even when an error also happened. Under set -e, a grep that finds nothing kills the script with status 1. Guard it with || true when no match is an acceptable result.

Context flags print neighbours, not records

-A, -B and -C add a fixed number of lines after, before or around each match. They do not know where a stack trace ends, so you pick the number by looking at your data first. The unhandled exception in the lab log is followed by a four-line Python traceback, and -A 4 captures exactly that block:

grep -A 4 printing a Python traceback after the error line, grep -A 1 printing a -- separator between match groups, and grep -n -B 1 marking context lines with a dash

When two match groups aren’t adjacent, grep prints -- between them. The user=deploy search shows it: line 1 and line 13 match, each brings one line of context, and the separator marks the gap. Groups that touch merge into one block with no separator, which is why grep -A 1 ERROR on this log printed six lines in a row.

With -n, matching lines get a colon after the number and context lines get a dash (3- versus 4:), so you can tell them apart after the fact.

The separator breaks tools that expect every line to be a log line, so you’ll want to control it when grep feeds another program:

  • --no-group-separator removes it
  • --group-separator="===" replaces it
  • -n keeps the colon and dash markers either way

ripgrep takes the same -A, -B and -C flags, and rg -A 4 "unhandled exception" logs/app.log printed the identical five lines. For records that really span lines, context counts are a guess, and -z further down is the exact tool.

grep -r searches everything you point it at

Recursive grep has no idea what a project is. Point grep -r TODO at a git checkout and it reads .git/, node_modules/, build output, hidden caches and binaries alike. In the lab project, it printed 13 lines of output, four of them from the sendemail-validate.sample hook that Git creates and one a binary-file notice. A recursive search walks a fixed set of places:

  • every regular file under the starting directory
  • hidden files and directories, .git included
  • binary files, reported on stderr instead of printed
  • symlinks only with -R, or when named on the command line

The symlink rule is the difference between -r and -R. The project has a shared-link symlink pointing at a sibling directory. grep -r skipped it, and grep -R followed it and printed webapp/shared-link/helpers.sh:TODO shared helper. If you run grep -r with no directory at all, GNU grep searches the current directory, which is handy and also different from ripgrep, as the next section shows.

Filters come next. --include and --exclude take a glob that’s matched against the file name, and --exclude-dir matches directory names. The one that catches people is brace syntax, because the globs grep uses do not support braces:

grep --include with quoted braces matching nothing, the shell expanding unquoted braces into two --include flags, and --exclude-dir trimming node_modules

Quoted, --include="*.{py,js}" matched nothing and exited 1, since no file name contains a literal brace. Unquoted, it worked, but only because bash expanded the braces into --include=*.py --include=*.js before grep ran, as the echo line proves.

That trick depends on your shell: bash and zsh expand braces, while sh on Ubuntu (dash) passes them through untouched, so the same line in a #!/bin/sh script matches nothing. Write two --include flags and quote both. The last command in the capture adds --exclude-dir for node_modules and build and returns just the two source files.

Hidden directories need their own glob. --exclude-dir=".*" skips .git and .cache in one flag, and combined with the two directory excludes it cut the lab project down to the five files in src/. One of those five was still a binary.

Never pair that glob with . as the path. --exclude-dir also applies to directories named on the command line, and . matches .*, so grep -rl --exclude-dir=".*" TODO . skipped the whole tree, printed nothing and exited 1. Leave the path off so grep searches the working directory, or name the directory, as in grep -rl --exclude-dir=".*" TODO webapp/.

grep: webapp/src/logo.bin: binary file matches

grep found the pattern inside a file that contains NUL bytes, so it refused to print the line and wrote this notice instead. Since grep 3.5 the notice goes to stderr, so it doesn’t inflate a | wc -l count.

-I skips binary files entirely, and grep -rlI TODO webapp/src/ listed four files with logo.bin gone. -a does the opposite and treats the file as text, which is what you want for a log that picked up a stray NUL byte.

-z changes what a line is

grep reads input as newline-terminated lines unless you give it -z. With -z, records end at a NUL byte instead, and a normal text file with no NULs becomes one record. That’s the trick for matching across lines: combine -z with -P, let (?s) make the dot match newlines, and use a lazy .*? so the match stops at the first closing brace:

grep -zoP "(?s)location /api \{.*?\}" conf/nginx.conf | tr "\0" "\n"

The whole location /api block comes back, and nothing from the /static block after it:

location /api {
        proxy_pass http://127.0.0.1:8080;
        proxy_read_timeout 30s;
    }

You need the tr at the end, because with -z grep also ends its output with a NUL instead of a newline. Without it, your prompt lands on the same line as the closing brace. A greedy .* would run to the last brace in the file, so keep the question mark.

-Z (capital) is a different flag with a related job: it ends each file name grep prints (for example with -l or -L) with a NUL, so xargs -0 can split names that contain spaces. The lab project has a file called release notes.txt, and plain xargs broke it in two:

grep -zoP extracting a multi-line nginx location block, xargs splitting a filename with a space, and grep -lZ with xargs -0 handling it

Without -Z, wc looked for files named webapp/src/release and notes.txt, failed on both, and the pipeline exited 123. With grep -rlZ and xargs -0, all five files were counted and the total went from 14 to 15 lines. The rule is short:

  • -z changes how grep reads input
  • -Z changes how grep prints file names
  • find -print0 and xargs -0 are the matching pair upstream and downstream

Going the other way, find -print0 into xargs -0 grep -H TODO fed the awkward file name to grep intact. You want -H there because xargs may hand grep a single file, and grep drops the file name when it searches only one.

ripgrep skips what grep reads

ripgrep is not a faster grep with the same defaults. It is recursive by default, it honours .ignore and .rgignore anywhere and .gitignore inside a git repository, and it skips hidden files, binary files and symlinks unless you ask. Both lab distros package it as ripgrep, and the binary is rg:

sudo apt install -y ripgrep

Check both tools before you compare them, because a ripgrep build without PCRE2 rejects -P outright. The Ubuntu package reports +pcre2 in its feature line:

Ubuntu 26.04.1 LTS with GNU grep 3.12 and ripgrep 15.1.0 built with PCRE2 10.43

The filtering shows up the moment you search the same project. rg -l TODO . listed four files where grep -r listed nine, and each -u peels back one layer of filtering:

  1. -u ignores .gitignore and friends (adds node_modules and build)
  2. -uu also searches hidden files (adds .cache and .git)
  3. -uuu also searches binary files (adds logo.bin)

The first command in the capture is the trap that sent the first ripgrep run in this lab sideways. Inside a script, over SSH or under cron, stdin is often a pipe rather than a terminal, and rg with no path searches that pipe instead of the current directory. The run printed nothing and exited 1 while the project was full of TODOs. Always pass the path, even if all you need is .:

rg returning nothing when stdin is a pipe, then rg -l, -u, -uu and -uuu adding ignored, hidden and binary files in a git project

Even -uuu leaves symlinks alone, which is why the list above has no shared-link. rg -L follows them the way grep -R does.

Filtering by type is shorter than the grep globs: rg -t py TODO . limits the search to Python files, -T yaml excludes YAML, and rg --type-list shows what each type covers (js includes *.cjs, *.jsx, *.mjs and *.vue). For one-off patterns, -g takes a glob and a leading ! negates it, so rg -l -uu -g "*.js" -g "!*.min.js" TODO . returned src/util.js and the node_modules copy without the minified build file.

The regex engine differs too. The default rg engine understands \d and \w without a flag, so you get 1840ms and 3000ms from rg -o "\d{4}ms" where plain grep found nothing. It does not do lookaround, and it says so instead of failing quietly.

error: look-around, including look-ahead and look-behind, is not supported

ripgrep printed this for rg -o "(?<=user=)\w+" and exited 2, along with a hint to enable PCRE2. Add -P (or --pcre2) and the same pattern printed deploy, reports, reports and deploy, matching grep -oP. A capture group with -r avoids the second engine entirely: rg -o 'user=(\w+)' -r '$1' produced the same four names. Keep $1 in single quotes, or your shell replaces it with an empty string first.

Multiline matching uses -U instead of -z. rg -U "location /api \{[^}]*\}" conf/nginx.conf printed the full four-line block with its original indentation and no NUL byte to clean up. Counting follows grep: rg -c for lines, --count-matches for matches. For a deeper tour of the ignore rules and the config file, the ripgrep user guide is the reference.

Which one belongs in a script? Use grep when the input is a file list, a pipe or a server where you can’t install anything, because GNU grep is on every Linux box and its defaults do not change with a .gitignore. Use rg when you’re searching a code tree interactively and want the ignored files gone.

If you move between the two, our grep, awk and sed comparison covers where field extraction and in-place edits take over from searching.

Time grep -r against rg on one tree

The speed claim is easy to check on your own machine, as long as you compare like with like. rg -uuu turns off every filter, so it reads the same files as grep -r. Counting the matching files from both proves they did the same work. The test tree was /usr/share on the lab VM, where nproc reports 2 CPUs: 25,531 files and 317 MB.

grep -r taking 3.09s on the first run and 0.30s warm against rg -uuu at 0.13s over 25,531 files in /usr/share, both finding 152 files

The first grep run took 3.09 s because it read the tree from disk. Every run after it hit the page cache. grep settled at 0.30 to 0.31 s and rg at 0.13 to 0.14 s, a bit over twice as fast. Both found sudo in 152 files, and a diff of the two sorted file lists came back identical.

That first grep run warmed the cache for every rg run after it, so the cold numbers need their own test. Drop the page cache before each tool (this needs sudo and slows the whole box for a moment):

sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; /usr/bin/time -f "rg cold: %es" rg -uuu -c sudo /usr/share >/dev/null
sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; /usr/bin/time -f "grep -r cold: %es" grep -r -c sudo /usr/share >/dev/null

Both tools hit one root-only file, and GNU time reports the exit status 2 that followed before printing each timing:

rg: /usr/share/chrony/chrony.keys: Permission denied (os error 13)
Command exited with non-zero status 2
rg cold: 1.61s
grep: /usr/share/chrony/chrony.keys: Permission denied
Command exited with non-zero status 2
grep -r cold: 1.90s

From a cold cache the gap shrinks to 1.61 s against 1.90 s, because both tools spend most of that time waiting on the disk. The 3.09 s from the very first grep run was also a cold start, so the same tool on the same tree landed anywhere from 1.90 s to 3.09 s cold. Expect cold numbers to swing from run to run, and compare them only side by side. The version capture also shows simd(runtime):+SSE2,-SSSE3,-AVX2, so on this virtual CPU rg ran without the SSSE3 and AVX2 code paths that most current hardware offers it. Treat the warm 2.2x as a figure from a basic CPU, not a ceiling. The bigger win for ripgrep on a real project is the work it skips, not the work it does faster: on a checkout with a large node_modules, the default rg never opens those files at all.

For more one-page references in the same format, the curl cheat sheet covers the HTTP side of the same scripts, the APT cheat sheet and the DNF5 cheat sheet handle packages, and every sheet with its PDF lives on the cheat sheets hub.

Pin the PDF where you’ll see it, and when a grep result looks too clean, rerun it with -c, -o | wc -l and the exit code side by side. Those three numbers are usually enough to tell you which flag did more, or less, than its name suggests.

Keep reading

Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) AI Claude Code Cheat Sheet: Commands, Shortcuts and Flags (PDF) OpenAI Codex CLI Cheat Sheet: Shortcuts, Commands, Flags (PDF) AI OpenAI Codex CLI Cheat Sheet: Shortcuts, Commands, Flags (PDF) macOS Keyboard Shortcuts Cheat Sheet (Golden Gate and Tahoe) Cheat Sheets macOS Keyboard Shortcuts Cheat Sheet (Golden Gate and Tahoe) uv Cheat Sheet: Python Package Manager Commands (PDF) Cheat Sheets uv Cheat Sheet: Python Package Manager Commands (PDF) DNF Cheat Sheet: dnf5 on Fedora, dnf on Rocky Linux 10 (PDF) Cheat Sheets DNF Cheat Sheet: dnf5 on Fedora, dnf on Rocky Linux 10 (PDF) Stratis Storage Cheat Sheet – reference guide Cheat Sheets Stratis Storage Cheat Sheet – reference guide

Leave a Comment

Press ESC to close