关于 ripgrep
一份 ripgrep(rg)使用指南,介绍如何用正则表达式递归搜索文件,并通过筛选和输出选项处理代码库及大型文本集合。
主要功能
- 01递归正则搜索
- 02按文件类型和 glob 筛选
- 03控制上下文与匹配输出
- 04多行及压缩文件搜索
- 05预览替换结果
适用场景
- 01查找代码库中的符号位置
- 02无需完整读取即可搜索大型文档
- 03定位包含或不含指定模式的文件
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ ratacat/ claude-skills --skill ripgrep安装后在 Claude Code 中输入/ripgrep确认已加载。
详细介绍
Ripgrep(rg)- 快速文本搜索工具
概述
Ripgrep 是一款面向行的搜索工具,可递归搜索目录中的正则表达式模式。它的速度比 grep 快 10-100 倍,并且默认遵循 .gitignore。可用它替代 grep、find,或手动阅读大型文件。
**核心原则:**需要在文件中查找文本时,请使用 ripgrep。能通过搜索找到内容时,不要将整个文件读入上下文。
适用场景
在以下情况下使用 ripgrep:
- 在代码库或目录中搜索文本模式
- 查找某个函数、变量或字符串的所有匹配项
- 搜索书籍、文档或大型文本文件
- 文件太大,无法完整读入上下文
- 同时在多个文件中查找特定内容
- 查找包含(或不包含)特定模式的文件
- 提取匹配行以供分析
以下情况请勿使用:
- 需要完整文件内容(使用 Read 工具)
- 只需按简单 glob 模式匹配文件名(使用 Glob 工具)
- 需要提取结构化数据(可考虑 jq、awk)
快速参考
| 任务 | 命令 |
|---|---|
| 基本搜索 | rg "pattern" [path] |
| 忽略大小写 | rg -i "pattern" |
| 智能大小写(自动) | rg -S "pattern" |
| 仅匹配完整单词 | rg -w "word" |
| 固定字符串(不使用正则表达式) | rg -F "literal.string" |
| 显示上下文行 | rg -C 3 "pattern"(前后各 3 行) |
| 显示行号 | rg -n "pattern"(在 tty 中默认显示) |
| 仅显示文件名 | rg -l "pattern" |
| 显示未匹配的文件 | rg --files-without-match "pattern" |
| 统计匹配数 | rg -c "pattern" |
| 仅显示匹配部分 | rg -o "pattern" |
| 反向匹配 | rg -v "pattern" |
| 多行搜索 | rg -U "pattern.*\nmore" |
文件筛选
按文件类型
Ripgrep 内置了文件类型定义。使用 -t 包含,使用 -T 排除:
# Search only Python files
rg -t py "def main"
# Search only JavaScript and TypeScript
rg -t js -t ts "import"
# Exclude test files
rg -T test "function"
# List all known types
rg --type-list
常见类型: py、js、ts、rust、go、java、c、cpp、rb、php、html、css、json、yaml、md、txt、sh
按 Glob 模式
# Only .tsx files
rg -g "*.tsx" "useState"
# Exclude node_modules (in addition to gitignore)
rg -g "!node_modules/**" "pattern"
# Only files in src directory
rg -g "src/**" "pattern"
# Multiple globs
rg -g "*.js" -g "*.ts" "pattern"
# Case insensitive globs
rg --iglob "*.JSON" "pattern"
按文件大小
# Skip files larger than 1MB
rg --max-filesize 1M "pattern"
目录控制
# Limit depth
rg --max-depth 2 "pattern"
# Search hidden files (dotfiles)
rg --hidden "pattern"
# Follow symlinks
rg -L "pattern"
# Ignore all ignore files (.gitignore, etc.)
rg --no-ignore "pattern"
# Progressive unrestricted (-u can stack up to 3 times)
rg -u "pattern" # --no-ignore
rg -uu "pattern" # --no-ignore --hidden
rg -uuu "pattern" # --no-ignore --hidden --binary
上下文选项
# Lines after match
rg -A 5 "pattern"
# Lines before match
rg -B 5 "pattern"
# Lines before and after
rg -C 5 "pattern"
# Print entire file on match (passthrough mode)
rg --passthru "pattern"
输出格式
# Just filenames with matches
rg -l "pattern"
# Files without matches
rg --files-without-match "pattern"
# Count matches per file
rg -c "pattern"
# Count total matches (not lines)
rg --count-matches "pattern"
# Only the matched text (not full line)
rg -o "pattern"
# JSON output (for parsing)
rg --json "pattern"
# Vim-compatible output (file:line:col:match)
rg --vimgrep "pattern"
# With statistics
rg --stats "pattern"
正则表达式模式
Ripgrep 默认使用 Rust 正则表达式语法:
# Alternation
rg "foo|bar"
# Character classes
rg "[0-9]+"
rg "[a-zA-Z_][a-zA-Z0-9_]*"
# Word boundaries
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
# Groups
rg "(foo|bar)baz"
# Lookahead/lookbehind (requires -P for PCRE2)
rg -P "(?<=prefix)content"
rg -P "content(?=suffix)"
多行匹配
# Enable multiline mode
rg -U "start.*\nend"
# Dot matches newline too
rg -U --multiline-dotall "start.*end"
# Match across lines
rg -U "function\s+\w+\([^)]*\)\s*\{"
替换(仅预览)
Ripgrep 可以显示替换后的效果(不会修改文件):
# Simple replacement
rg "old" -r "new"
# Using capture groups
rg "(\w+)@(\w+)" -r "$2::$1"
# Remove matches (empty replacement)
rg "pattern" -r ""
搜索特殊文件
压缩文件
# Search in gzip, bzip2, xz, lz4, lzma, zstd files
rg -z "pattern" file.gz
rg -z "pattern" archive.tar.gz
二进制文件
# Include binary files
rg --binary "pattern"
# Treat binary as text (may produce garbage)
rg -a "pattern"
大型文件
对于太大而无法读入上下文的文件:
# Search and show only matching lines
rg "specific pattern" large_file.txt
# Limit matches to first N per file
rg -m 10 "pattern" huge_file.log
# Show byte offset for large file navigation
rg -b "pattern" large_file.txt
# Use with head/tail for pagination
rg "pattern" large_file.txt | head -100
性能提示
- 指定具体路径 - 知道子目录时,不要从根目录开始搜索
- 使用文件类型 -
-t py比-g "*.py"更快 - 使用固定字符串 - 不需要正则表达式时使用
-F - 限制深度 - 知道目录结构时使用
--max-depth - 让 gitignore 生效 - 除非确有需要,否则不要使用
--no-ignore - 使用单词边界 -
-w已经过优化
常见模式
查找函数定义
# Python
rg "def \w+\(" -t py
# JavaScript/TypeScript
rg "(function|const|let|var)\s+\w+\s*=" -t js -t ts
rg "^\s*(async\s+)?function" -t js
# Go
rg "^func\s+\w+" -t go
查找导入语句/require 语句
# Python
rg "^(import|from)\s+" -t py
# JavaScript
rg "^(import|require\()" -t js
# Go
rg "^import\s+" -t go
查找 TODO/FIXME 注释
rg "(TODO|FIXME|HACK|XXX):"
查找错误处理
# Python
rg "except\s+\w+:" -t py
# JavaScript
rg "\.catch\(|catch\s*\(" -t js
查找类定义
# Python
rg "^class\s+\w+" -t py
# JavaScript/TypeScript
rg "^(export\s+)?(default\s+)?class\s+\w+" -t js -t ts
在书籍/文档中搜索
# Find chapter headings
rg "^(Chapter|CHAPTER)\s+\d+" book.txt
# Find quoted text
rg '"[^"]{20,}"' document.txt
# Find paragraphs containing word
rg -C 2 "keyword" book.txt
与其他工具组合使用
# Find files, then search
rg --files | xargs rg "pattern"
# Search and count by file
rg -c "pattern" | sort -t: -k2 -rn
# Search and open in editor
rg -l "pattern" | xargs code
# Extract unique matches
rg -o "\b[A-Z]{2,}\b" | sort -u
# Search multiple patterns from file
rg -f patterns.txt
退出代码
| 代码 | 含义 |
|---|---|
| 0 | 找到匹配项 |
| 1 | 未找到匹配项 |
| 2 | 发生错误 |
适用于脚本编写:
if rg -q "pattern" file.txt; then
echo "Found"
fi
常见错误
| 错误 | 修正方法 |
|---|---|
| 模式包含特殊字符 | 对固定字符串使用 -F,或进行转义:rg "foo\.bar" |
| 找不到隐藏文件 | 添加 --hidden 或 -uu |
| 缺少 node_modules | 添加 --no-ignore(但通常跳过它才是正确做法) |
| 正则表达式过于复杂 | 尝试使用支持前瞻/后顾的 PCRE2:-P |
| 输出过长 | 使用 -m N 限制输出,或使用 -l 仅显示文件名 |
| 跳过了二进制文件 | 添加 --binary,或使用 -a 以文本模式搜索 |
| 需要查看完整行 | 移除 -o(仅匹配)标志 |
何时优先使用其他工具
| 任务 | 更合适的工具 |
|---|---|
| 结构化 JSON 查询 | jq |
| 按列处理文本 | awk |
| 流编辑/替换 | sed(会实际修改文件) |
| 仅按名称查找文件 | fd 或 find |
| 简单列出文件 | ls 或 glob |
| 需要完整文件内容 | Read 工具 |
评论
支持 Markdown