RipGrep RG
🛠 Ripgrep (rg) Power-User Cheat Sheet
ripgrep is a line-oriented search tool that recursively searches your current directory for a regex pattern. It is faster than grep because it respects your .gitignore and skips hidden files by default.
1. The Essentials (Common Flags)
| Flag | Name | Description |
|---|---|---|
-i |
--ignore-case |
Case-insensitive search. |
-S |
--smart-case |
Search case-insensitively if the pattern is all lowercase. |
-v |
--invert-match |
Show lines that do not match the pattern. |
-w |
--word-regexp |
Only match whole words. |
-z |
--search-zip |
Search inside compressed files (gz, bz2, etc.). |
-P |
--pcre2 |
Enable Perl-Compatible Regular Expressions (for \K, lookaheads). |
2. Output Formatting (Wiki/Scripting)
These are vital when you want to pipe data into CSVs, logs, or other scripts.
| Flag | Description |
|---|---|
-o |
Only matching: Only print the matching part of the line. |
-N |
No line numbers: Suppress the 1: prefix. |
-I |
No filename: Don't print the file name header/prefix. |
-h |
No filename (alias): Useful for cleaning up output. |
-r |
Replace: Replace matches with specific text (uses $1, $2 for groups). |
-C <N> |
Context: Show N lines before and after match. (-A for after, -B for before). |
3. Practical Examples
The "Data Extractor" (Your HL7 use-case)
Extract specific IDs and strip away everything else for a clean list:
# Finds 'ID|', drops the label via \K, takes alphanumeric chars, ignores filenames
rg -PNIho "ID\|\K[A-Z0-9]+" *.hl7
Searching Your NixOS Config
Find where you defined a specific package across all .nix files:
rg "services.openssh" /etc/nixos/
Finding Files by Type
Only search inside Python or YAML files:
rg "database_url" -tyaml -tpython
(Use rg --type-list to see all available shortcuts)
Search and Replace (Dry Run)
See what a replacement would look like without changing the file:
rg "old-api-v1" --replace "new-api-v2"
4. Advanced: The "Keep" Operator (\K)
The \K operator is a "match reset." It is the cleanest way to find a prefix but exclude it from the final result.
Logic Flow:
- Match:
label_name: - Reset:
\K(The engine forgets everything matched so far) - Capture:
\d+(Only this part is returned if using-o)
5. Config/Aliases for your .bashrc or zshrc
Since you're on NixOS, you can add these to your home-manager or configuration.nix aliases:
# 'rgl' - rg for Logs (case insensitive, no line numbers, no filename)
alias rgl='rg -iNIh'
# 'rgp' - rg with PCRE2 enabled by default
alias rgp='rg -P'