ast-grep
TLDR
Search for a pattern in the current directory
SYNOPSIS
ast-grep [command] [options]
sg [command] [options]
DESCRIPTION
ast-grep (also invoked as sg) is a structural code search and rewriting tool. Unlike text-based grep, it parses code into an Abstract Syntax Tree (AST) and matches patterns at the syntactic level, ensuring matches respect code structure.
Patterns use a code-like syntax where $METAVARIABLES match any expression. For example, console.log($MSG) matches any console.log call regardless of its argument. This enables precise refactoring that text-based tools cannot achieve.
The tool supports multiple languages through tree-sitter parsers, including JavaScript, TypeScript, Python, Rust, Go, C, C++, Java, and more. The scan command applies rules from YAML configuration files, enabling project-wide linting and enforcement of code patterns.
Configuration files (sgconfig.yml) define rule directories and project settings. Individual rules specify patterns, rewrites, severity levels, and file filters.
PARAMETERS
run
Run a one-time search or rewrite (default command)scan
Scan and rewrite code using configuration rulestest
Test ast-grep rulesnew
Create new ast-grep project, rules, or testslsp
Start language server for IDE integration-p pattern, --pattern pattern
AST pattern to search for; use $VAR for metavariables-r replacement, --rewrite replacement
Replacement pattern for matches-l lang, --lang lang
Target language (javascript, typescript, python, rust, go, etc.)-i, --interactive
Interactive mode for confirming rewrites--json [style]
Output in JSON format (pretty, stream, compact)-A num, --after num
Show num lines after each match-B num, --before num
Show num lines before each match-C num, --context num
Show num lines around each match--stdin
Read code from standard input--threads num
Number of threads (0 for auto-detection)-c file, --config file
Path to config file (default: sgconfig.yml)
CAVEATS
The sg alias conflicts with the Linux setgroups command; use the full ast-grep command or create a custom alias. Pattern syntax varies slightly by language due to AST differences. Complex patterns may require understanding tree-sitter node types.
HISTORY
ast-grep was created by Herrington Darkholme and released in 2022. Written in Rust for performance, it was designed to bring structural code search to the command line, inspired by tools like Semgrep and Comby. The tool gained popularity for its speed and intuitive pattern syntax for code refactoring tasks.


