Use when searching for or transforming code patterns structurally - provides ast-grep CLI syntax, metavariable patterns, and language-specific examples for precise AST-based code search and rewriting
View on GitHubplugins/tooling/skills/howto-ast-grep/SKILL.md
February 3, 2026
Select agents to install to:
npx add-skill https://github.com/pbdeuchler/llm-plugins/blob/main/plugins/tooling/skills/howto-ast-grep/SKILL.md -a claude-code --skill howto-ast-grepInstallation paths:
.claude/skills/howto-ast-grep/# Using ast-grep for Structural Code Search
## Overview
ast-grep (`sg`) matches code by AST structure, not text. Use it instead of grep/ripgrep when you need to match code patterns regardless of whitespace, variable names, or formatting. Patterns must be valid, parsable code in the target language.
## When to Use
**Prefer ast-grep over grep when:**
- Finding function calls with specific argument shapes
- Matching patterns where variable names differ but structure is the same
- Rewriting code patterns across a codebase (migrations, deprecations)
- Finding anti-patterns that regex can't express (e.g. "await inside a loop")
**Use grep instead when:**
- Searching for string literals, comments, or non-code text
- Simple keyword search (import names, error messages)
- ast-grep is not installed
## CLI Quick Reference
```bash
# Search for a pattern
sg run -p 'console.log($$$ARGS)' -l javascript src/
# Search and replace (interactive)
sg run -p '$A && $A()' -r '$A?.()' -l typescript --interactive src/
# Apply all replacements without prompting
sg run -p 'var $X = $Y' -r 'const $X = $Y' -l javascript -U src/
# JSON output for programmatic use
sg run -p '$FUNC($$$)' -l python --json src/
# Read from stdin
echo 'let x = 1' | sg run -p 'let $X = $Y' -l javascript --stdin
```
## Metavariable Syntax
| Syntax | Matches | Example |
|--------|---------|---------|
| `$NAME` | Exactly one AST node | `console.log($MSG)` matches `console.log("hi")` but not `console.log("hi", 2)` |
| `$$$NAME` | Zero or more nodes | `console.log($$$ARGS)` matches any number of arguments |
| `$_NAME` | One node, non-capturing | `$_OBJ.$METHOD()` matches without binding `$_OBJ` |
**Reuse enforces equality:** `$A == $A` matches `x == x` but not `x == y`.
## Language-Specific Patterns
Always pass `-l <language>`. The language determines how patterns are parsed.
**JavaScript/TypeScript:**
```bash
# Find React hooks
sg run -p 'use$HOOK($$$)' -l typescript src/
# Optional chaining candidates