ast-grep
A CLI tool for code structural search, lint, and rewriting using Abstract Syntax Trees.
ast-grep (also known as sg) is a CLI tool for code structural search, lint,
and rewriting using Abstract Syntax Trees. Unlike text-based tools like grep or
sed, ast-grep matches code by its syntactic structure, making it possible to
write precise, language-aware search and replace patterns across large codebases.
It supports over 20 programming languages via tree-sitter grammars.
Features
- Structural search and replace — match code patterns using AST nodes instead of text, then rewrite matches with metavariable capture
- Intuitive pattern syntax — write patterns as ordinary code with
$VARmetavariables, no complex query language required - Multi-language support — works with JavaScript, TypeScript, Python, Rust, Go, Java, C, C++, and many more via tree-sitter
- Custom linting — define rules in YAML with pattern matching, fix suggestions, and pretty error reporting
- High performance — written in Rust with multi-threaded file traversal for fast results across thousands of files
- Interactive codemod — review and confirm each replacement interactively before applying changes
- Programmatic API — Node.js bindings with a jQuery-like API for AST traversal and manipulation
Installation
cargo install ast-grep --locked
Or via package managers:
# Debian / Ubuntu / Fedora
# Install via npm (works on all Linux distributions)
npm install --global @ast-grep/cli
# macOS
brew install ast-grep
# Arch Linux
pacman -S ast-grep
# Nix
nix-shell -p ast-grep
# pip
pip install ast-grep-cliUsage
# Search for a pattern in the current directory
sg -p 'console.log($MSG)'
# Search in a specific language
sg -p '$PROP && $PROP()' -l ts
# Replace a pattern across files
sg -p '$PROP && $PROP()' -r '$PROP?.()' -l ts
# Interactive codemod — review each replacement before applying
sg -p '$PROP && $PROP()' -r '$PROP?.()' --interactive -l ts
# Scan project with custom lint rules
sg scan
# Run a single rule from a YAML file
sg scan -r my-rule.ymlConfiguration
ast-grep uses a sgconfig.yml file for project-level configuration and custom
rules. Initialize a project with:
sg new
Define custom lint rules in YAML:
id: no-console-log
language: TypeScript
rule:
pattern: console.log($$$ARGS)
message: Remove console.log before committing
severity: warning
fix: ""Why ast-grep over grep/sed?
| Capability | grep/sed | ast-grep |
|---|---|---|
| Match type | Text / regex | AST structure |
| Understands nesting | No | Yes |
| Language-aware | No | 20+ languages |
| Refactoring | Fragile | Precise |
| Custom lint rules | No | YAML-based |
| Interactive mode | No | Yes |