ripgrep

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ripgrep (rg) - Fast Text Search Tool

Ripgrep (rg) - 快速文本搜索工具

Overview

概述

Ripgrep is a line-oriented search tool that recursively searches directories for regex patterns. It's 10-100x faster than grep and respects
.gitignore
by default. Use it instead of grep, find, or manually reading large files.
Core principle: When you need to find text in files, use ripgrep. Don't read entire files into context when you can search them.
Ripgrep 是一款面向行的搜索工具,可递归搜索目录中的正则表达式模式。它的速度比 grep 快 10-100 倍,并且默认遵循
.gitignore
规则。可以用它替代 grep、find 或手动读取大文件。
核心原则: 当你需要在文件中查找文本时,使用 ripgrep。能搜索解决的问题,就不要把整个文件内容读入上下文。

When to Use

使用场景

Use ripgrep when:
  • Searching for text patterns across a codebase or directory
  • Finding all occurrences of a function, variable, or string
  • Searching through books, documentation, or large text files
  • Files are too large to read fully into context
  • Looking for specific content in many files at once
  • Finding files that contain (or don't contain) certain patterns
  • Extracting matching lines for analysis
Don't use when:
  • You need the full file content (use Read tool)
  • Simple glob pattern matching for filenames only (use Glob tool)
  • You need structured data extraction (consider jq, awk)
适合使用 ripgrep 的场景:
  • 在代码库或目录中搜索文本模式
  • 查找函数、变量或字符串的所有出现位置
  • 搜索书籍、文档或大型文本文件
  • 文件过大,无法完整读入上下文
  • 同时在多个文件中查找特定内容
  • 查找包含(或不包含)特定模式的文件
  • 提取匹配行用于分析
不适合使用的场景:
  • 需要完整文件内容(使用读取工具)
  • 仅对文件名进行简单 glob 模式匹配(使用 Glob 工具)
  • 需要结构化数据提取(可考虑 jq、awk)

Quick Reference

快速参考

TaskCommand
Basic search
rg "pattern" [path]
Case insensitive
rg -i "pattern"
Smart case (auto)
rg -S "pattern"
Whole word only
rg -w "word"
Fixed string (no regex)
rg -F "literal.string"
Show context lines
rg -C 3 "pattern"
(3 before & after)
Show line numbers
rg -n "pattern"
(default in tty)
Only filenames
rg -l "pattern"
Files without match
rg --files-without-match "pattern"
Count matches
rg -c "pattern"
Only matching part
rg -o "pattern"
Invert match
rg -v "pattern"
Multiline search
rg -U "pattern.*\nmore"
任务命令
基础搜索
rg "pattern" [path]
忽略大小写
rg -i "pattern"
智能大小写(自动适配)
rg -S "pattern"
仅匹配整词
rg -w "word"
固定字符串(禁用正则)
rg -F "literal.string"
显示上下文行
rg -C 3 "pattern"
(前后各3行)
显示行号
rg -n "pattern"
(终端环境默认开启)
仅显示文件名
rg -l "pattern"
显示无匹配的文件
rg --files-without-match "pattern"
统计匹配次数
rg -c "pattern"
仅显示匹配部分
rg -o "pattern"
反向匹配
rg -v "pattern"
多行搜索
rg -U "pattern.*\nmore"

File Filtering

文件过滤

By File Type

按文件类型

Ripgrep has built-in file type definitions. Use
-t
to include,
-T
to exclude:
bash
undefined
Ripgrep 内置了文件类型定义。使用
-t
包含指定类型,
-T
排除指定类型:
bash
undefined

Search only Python files

仅搜索 Python 文件

rg -t py "def main"
rg -t py "def main"

Search only JavaScript and TypeScript

仅搜索 JavaScript 和 TypeScript 文件

rg -t js -t ts "import"
rg -t js -t ts "import"

Exclude test files

排除测试文件

rg -T test "function"
rg -T test "function"

List all known types

列出所有支持的文件类型

rg --type-list

**Common types:** `py`, `js`, `ts`, `rust`, `go`, `java`, `c`, `cpp`, `rb`, `php`, `html`, `css`, `json`, `yaml`, `md`, `txt`, `sh`
rg --type-list

**常见类型:** `py`, `js`, `ts`, `rust`, `go`, `java`, `c`, `cpp`, `rb`, `php`, `html`, `css`, `json`, `yaml`, `md`, `txt`, `sh`

By Glob Pattern

按 Glob 模式

bash
undefined
bash
undefined

Only .tsx files

仅搜索 .tsx 文件

rg -g "*.tsx" "useState"
rg -g "*.tsx" "useState"

Exclude node_modules (in addition to gitignore)

排除 node_modules(在 gitignore 规则基础上额外排除)

rg -g "!node_modules/**" "pattern"
rg -g "!node_modules/**" "pattern"

Only files in src directory

仅搜索 src 目录下的文件

rg -g "src/**" "pattern"
rg -g "src/**" "pattern"

Multiple globs

多个 Glob 模式

rg -g ".js" -g ".ts" "pattern"
rg -g ".js" -g ".ts" "pattern"

Case insensitive globs

忽略大小写的 Glob 模式

rg --iglob "*.JSON" "pattern"
undefined
rg --iglob "*.JSON" "pattern"
undefined

By File Size

按文件大小

bash
undefined
bash
undefined

Skip files larger than 1MB

跳过大于 1MB 的文件

rg --max-filesize 1M "pattern"
undefined
rg --max-filesize 1M "pattern"
undefined

Directory Control

目录控制

bash
undefined
bash
undefined

Limit depth

限制搜索深度

rg --max-depth 2 "pattern"
rg --max-depth 2 "pattern"

Search hidden files (dotfiles)

搜索隐藏文件(点文件)

rg --hidden "pattern"
rg --hidden "pattern"

Follow symlinks

跟随符号链接

rg -L "pattern"
rg -L "pattern"

Ignore all ignore files (.gitignore, etc.)

忽略所有忽略规则文件(.gitignore 等)

rg --no-ignore "pattern"
rg --no-ignore "pattern"

Progressive unrestricted (-u can stack up to 3 times)

逐步解除限制(-u 最多可叠加3次)

rg -u "pattern" # --no-ignore rg -uu "pattern" # --no-ignore --hidden rg -uuu "pattern" # --no-ignore --hidden --binary
undefined
rg -u "pattern" # --no-ignore rg -uu "pattern" # --no-ignore --hidden rg -uuu "pattern" # --no-ignore --hidden --binary
undefined

Context Options

上下文选项

bash
undefined
bash
undefined

Lines after match

显示匹配行之后的内容

rg -A 5 "pattern"
rg -A 5 "pattern"

Lines before match

显示匹配行之前的内容

rg -B 5 "pattern"
rg -B 5 "pattern"

Lines before and after

显示匹配行前后的内容

rg -C 5 "pattern"
rg -C 5 "pattern"

Print entire file on match (passthrough mode)

匹配时输出整个文件内容(直通模式)

rg --passthru "pattern"
undefined
rg --passthru "pattern"
undefined

Output Formats

输出格式

bash
undefined
bash
undefined

Just filenames with matches

仅显示包含匹配的文件名

rg -l "pattern"
rg -l "pattern"

Files without matches

显示无匹配的文件名

rg --files-without-match "pattern"
rg --files-without-match "pattern"

Count matches per file

按文件统计匹配次数

rg -c "pattern"
rg -c "pattern"

Count total matches (not lines)

统计总匹配次数(非行数)

rg --count-matches "pattern"
rg --count-matches "pattern"

Only the matched text (not full line)

仅显示匹配的文本(而非整行)

rg -o "pattern"
rg -o "pattern"

JSON output (for parsing)

JSON 格式输出(用于解析)

rg --json "pattern"
rg --json "pattern"

Vim-compatible output (file:line:col:match)

Vim 兼容格式输出(文件:行:列:匹配内容)

rg --vimgrep "pattern"
rg --vimgrep "pattern"

With statistics

显示搜索统计信息

rg --stats "pattern"
undefined
rg --stats "pattern"
undefined

Regex Patterns

正则表达式模式

Ripgrep uses Rust regex syntax by default:
bash
undefined
Ripgrep 默认使用 Rust 正则语法:
bash
undefined

Alternation

分支匹配

rg "foo|bar"
rg "foo|bar"

Character classes

字符类

rg "[0-9]+" rg "[a-zA-Z_][a-zA-Z0-9_]*"
rg "[0-9]+" rg "[a-zA-Z_][a-zA-Z0-9_]*"

Word boundaries

单词边界

rg "\bword\b"
rg "\bword\b"

Quantifiers

量词

rg "colou?r" # 0 or 1 rg "go+gle" # 1 or more rg "ha*" # 0 or more rg "x{2,4}" # 2 to 4 times
rg "colou?r" # 0 或 1 次 rg "go+gle" # 1 或多次 rg "ha*" # 0 或多次 rg "x{2,4}" # 2 到 4 次

Groups

分组

rg "(foo|bar)baz"
rg "(foo|bar)baz"

Lookahead/lookbehind (requires -P for PCRE2)

正向预查/反向预查(需要使用 -P 开启 PCRE2)

rg -P "(?<=prefix)content" rg -P "content(?=suffix)"
undefined
rg -P "(?<=prefix)content" rg -P "content(?=suffix)"
undefined

Multiline Matching

多行匹配

bash
undefined
bash
undefined

Enable multiline mode

启用多行模式

rg -U "start.*\nend"
rg -U "start.*\nend"

Dot matches newline too

点号匹配换行符

rg -U --multiline-dotall "start.*end"
rg -U --multiline-dotall "start.*end"

Match across lines

跨行匹配

rg -U "function\s+\w+([^)])\s{"
undefined
rg -U "function\s+\w+([^)])\s{"
undefined

Replacement (Preview Only)

替换功能(仅预览)

Ripgrep can show what replacements would look like (doesn't modify files):
bash
undefined
Ripgrep 可以展示替换效果(不会修改文件):
bash
undefined

Simple replacement

简单替换

rg "old" -r "new"
rg "old" -r "new"

Using capture groups

使用捕获组

rg "(\w+)@(\w+)" -r "$2::$1"
rg "(\w+)@(\w+)" -r "$2::$1"

Remove matches (empty replacement)

删除匹配内容(替换为空)

rg "pattern" -r ""
undefined
rg "pattern" -r ""
undefined

Searching Special Files

特殊文件搜索

Compressed Files

压缩文件

bash
undefined
bash
undefined

Search in gzip, bzip2, xz, lz4, lzma, zstd files

在 gzip、bzip2、xz、lz4、lzma、zstd 压缩文件中搜索

rg -z "pattern" file.gz rg -z "pattern" archive.tar.gz
undefined
rg -z "pattern" file.gz rg -z "pattern" archive.tar.gz
undefined

Binary Files

二进制文件

bash
undefined
bash
undefined

Include binary files

包含二进制文件

rg --binary "pattern"
rg --binary "pattern"

Treat binary as text (may produce garbage)

将二进制文件视为文本处理(可能产生乱码)

rg -a "pattern"
undefined
rg -a "pattern"
undefined

Large Files

大文件

For files too large to read into context:
bash
undefined
针对过大无法读入上下文的文件:
bash
undefined

Search and show only matching lines

搜索并仅显示匹配行

rg "specific pattern" large_file.txt
rg "specific pattern" large_file.txt

Limit matches to first N per file

限制每个文件的匹配次数为前 N 次

rg -m 10 "pattern" huge_file.log
rg -m 10 "pattern" huge_file.log

Show byte offset for large file navigation

显示匹配内容的字节偏移量,方便大文件导航

rg -b "pattern" large_file.txt
rg -b "pattern" large_file.txt

Use with head/tail for pagination

结合 head/tail 进行分页

rg "pattern" large_file.txt | head -100
undefined
rg "pattern" large_file.txt | head -100
undefined

Performance Tips

性能优化技巧

  1. Be specific with paths - Don't search from root when you know the subdir
  2. Use file types -
    -t py
    is faster than
    -g "*.py"
  3. Use fixed strings -
    -F
    when you don't need regex
  4. Limit depth -
    --max-depth
    when you know structure
  5. Let gitignore work - Don't use
    --no-ignore
    unless needed
  6. Use word boundaries -
    -w
    is optimized
  1. 指定具体路径 - 知道子目录时,不要从根目录开始搜索
  2. 使用文件类型参数 -
    -t py
    -g "*.py"
    速度更快
  3. 使用固定字符串模式 - 不需要正则时用
    -F
  4. 限制搜索深度 - 已知目录结构时使用
    --max-depth
  5. 利用 gitignore 规则 - 除非必要,不要使用
    --no-ignore
  6. 使用整词匹配 -
    -w
    经过优化,速度更快

Common Patterns

常见使用模式

Find function definitions

查找函数定义

bash
undefined
bash
undefined

Python

Python

rg "def \w+(" -t py
rg "def \w+(" -t py

JavaScript/TypeScript

JavaScript/TypeScript

rg "(function|const|let|var)\s+\w+\s*=" -t js -t ts rg "^\s*(async\s+)?function" -t js
rg "(function|const|let|var)\s+\w+\s*=" -t js -t ts rg "^\s*(async\s+)?function" -t js

Go

Go

rg "^func\s+\w+" -t go
undefined
rg "^func\s+\w+" -t go
undefined

Find imports/requires

查找导入语句

bash
undefined
bash
undefined

Python

Python

rg "^(import|from)\s+" -t py
rg "^(import|from)\s+" -t py

JavaScript

JavaScript

rg "^(import|require()" -t js
rg "^(import|require()" -t js

Go

Go

rg "^import\s+" -t go
undefined
rg "^import\s+" -t go
undefined

Find TODO/FIXME comments

查找 TODO/FIXME 注释

bash
rg "(TODO|FIXME|HACK|XXX):"
bash
rg "(TODO|FIXME|HACK|XXX):"

Find error handling

查找错误处理代码

bash
undefined
bash
undefined

Python

Python

rg "except\s+\w+:" -t py
rg "except\s+\w+:" -t py

JavaScript

JavaScript

rg ".catch(|catch\s*(" -t js
undefined
rg ".catch(|catch\s*(" -t js
undefined

Find class definitions

查找类定义

bash
undefined
bash
undefined

Python

Python

rg "^class\s+\w+" -t py
rg "^class\s+\w+" -t py

JavaScript/TypeScript

JavaScript/TypeScript

rg "^(export\s+)?(default\s+)?class\s+\w+" -t js -t ts
undefined
rg "^(export\s+)?(default\s+)?class\s+\w+" -t js -t ts
undefined

Search in books/documents

在书籍/文档中搜索

bash
undefined
bash
undefined

Find chapter headings

查找章节标题

rg "^(Chapter|CHAPTER)\s+\d+" book.txt
rg "^(Chapter|CHAPTER)\s+\d+" book.txt

Find quoted text

查找引用文本

rg '"[^"]{20,}"' document.txt
rg '"[^"]{20,}"' document.txt

Find paragraphs containing word

查找包含关键词的段落

rg -C 2 "keyword" book.txt
undefined
rg -C 2 "keyword" book.txt
undefined

Combining with Other Tools

与其他工具结合使用

bash
undefined
bash
undefined

Find files, then search

先查找文件,再搜索内容

rg --files | xargs rg "pattern"
rg --files | xargs rg "pattern"

Search and count by file

搜索并按文件统计匹配次数排序

rg -c "pattern" | sort -t: -k2 -rn
rg -c "pattern" | sort -t: -k2 -rn

Search and open in editor

搜索并在编辑器中打开文件

rg -l "pattern" | xargs code
rg -l "pattern" | xargs code

Extract unique matches

提取唯一匹配内容

rg -o "\b[A-Z]{2,}\b" | sort -u
rg -o "\b[A-Z]{2,}\b" | sort -u

Search multiple patterns from file

从文件中读取多个模式进行搜索

rg -f patterns.txt
undefined
rg -f patterns.txt
undefined

Exit Codes

退出码

CodeMeaning
0Matches found
1No matches found
2Error occurred
Useful for scripting:
bash
if rg -q "pattern" file.txt; then
    echo "Found"
fi
代码含义
0找到匹配内容
1未找到匹配内容
2发生错误
适用于脚本编写:
bash
if rg -q "pattern" file.txt; then
    echo "找到匹配"
fi

Common Mistakes

常见错误

MistakeFix
Pattern has special charsUse
-F
for fixed strings or escape:
rg "foo\.bar"
Can't find hidden filesAdd
--hidden
or
-uu
Missing node_modulesAdd
--no-ignore
(but it's usually right to skip)
Regex too complexTry
-P
for PCRE2 with lookahead/lookbehind
Output too longUse
-m N
to limit, or
-l
for just filenames
Binary file skippedAdd
--binary
or
-a
for text mode
Need to see full lineRemove
-o
(only-matching) flag
错误解决方法
模式包含特殊字符使用
-F
启用固定字符串模式,或转义特殊字符:
rg "foo\.bar"
无法找到隐藏文件添加
--hidden
-uu
参数
未搜索 node_modules添加
--no-ignore
(但通常跳过是正确选择)
正则表达式过于复杂尝试使用
-P
开启 PCRE2 以支持预查功能
输出内容过长使用
-m N
限制匹配次数,或
-l
仅显示文件名
二进制文件被跳过添加
--binary
-a
以文本模式处理
需要查看完整行移除
-o
(仅显示匹配部分)参数

When to Prefer Other Tools

何时优先使用其他工具

TaskBetter Tool
Structured JSON queries
jq
Column-based text processing
awk
Stream editing/substitution
sed
(actually modifies files)
Find files by name only
fd
or
find
Simple file listing
ls
or
glob
Full file content neededRead tool
任务更合适的工具
结构化 JSON 查询
jq
基于列的文本处理
awk
流编辑/替换(实际修改文件)
sed
仅按文件名查找文件
fd
find
简单文件列表
ls
glob
需要完整文件内容读取工具