sg
AST-based structural code search tool
TLDR
Search for a pattern in the current directory
SYNOPSIS
sg command [options] [paths...]
DESCRIPTION
sg (ast-grep) is a fast CLI tool for structural code search, linting, and rewriting based on abstract syntax trees. Unlike text-based grep, it understands code syntax and matches patterns at the AST level, making searches more precise and language-aware.
Patterns use a familiar code-like syntax with metavariables ($VAR, $$$ARGS) to match arbitrary expressions. For example, console.log($MSG) matches any console.log call regardless of the argument. Multiple metavariables with the same name must match identical code.
The tool supports many languages including JavaScript, TypeScript, Python, Rust, Go, Java, C, C++, and more via tree-sitter parsers. Rules can be defined in YAML configuration files for consistent codebase scanning.
PARAMETERS
-p, --pattern pattern
AST pattern to match; use $VAR for wildcards-r, --rewrite replacement
String to replace matched AST nodes-l, --lang language
Specify the programming language--selector kind
Extract specific AST node type from matches--strictness level
Matching strictness (cst, smart, ast, relaxed, signature)-i, --interactive
Start interactive editing session-U, --update-all
Apply all rewrites without confirmation--json[=style]
Output as JSON (pretty, stream, compact)-A num
Show lines after match-B num
Show lines before match-C num
Show context lines around match-c, --config file
Path to configuration file (default: sgconfig.yml)
COMMANDS
run
Search code by pattern and optionally rewrite (default command)scan
Scan codebase using configuration files and rulestest
Run tests for ast-grep rulesnew
Generate scaffolding files (project, rule, test, util)lsp
Start Language Server Protocol for editor integrationcompletions
Generate shell completion scripts
CAVEATS
On Linux, sg may conflict with the system sg command (setgroups). Use the full name ast-grep or create an alias. Pattern syntax varies slightly between languages due to AST differences.
HISTORY
ast-grep was created by Herrington Darkholme and first released around 2022. Written in Rust with tree-sitter for parsing, it was designed as a modern alternative to text-based code search tools, enabling precise structural matching across multiple programming languages.
