Skip to content

Instantly share code, notes, and snippets.

@dsaad68
Created November 21, 2025 17:53
Show Gist options
  • Select an option

  • Save dsaad68/0cc94357515627352997839b8be15063 to your computer and use it in GitHub Desktop.

Select an option

Save dsaad68/0cc94357515627352997839b8be15063 to your computer and use it in GitHub Desktop.
Structured Grep with Context

sgrep - Structured Grep with Context

Description

sgrep is a bash function that searches for patterns in files matching a specific path pattern and returns results with configurable context lines. It first lists all files matching the path pattern, then performs the search using ripgrep with syntax highlighting and line numbers.

For AI Agents:

This tool searches codebases for specific patterns within filtered file paths. 
Use it to find code snippets, TODO comments, function definitions, or any text pattern in a structured way. 
It returns results with surrounding context lines, making it ideal for understanding code usage and implementation details. 
Specify path patterns using glob syntax (e.g., `src/**/*.py` for Python files, `*.ts` for TypeScript) and search patterns using regex.

Installation

Required

ripgrep - Fast search tool with glob support

# macOS
brew install ripgrep

# Ubuntu/Debian
sudo apt install ripgrep

# Fedora
sudo dnf install ripgrep

# Arch
sudo pacman -S ripgrep

# From cargo
cargo install ripgrep

Setup

Add the function to your shell configuration:

# Add to ~/.bashrc or ~/.zshrc
sgrep() {
    local path_pattern="$1"
    local search_pattern="$2"
    local n="${3:-3}"
    local max_results="${4:-}"
    
    if [ -z "$path_pattern" ] || [ -z "$search_pattern" ]; then
        echo "Usage: sgrep <path_pattern> <search_pattern> [context_lines=3] [max_results=all]"
        return 1
    fi
    
    local rg_cmd="rg '$search_pattern' \
        --context $n \
        --heading \
        --line-number \
        --color always \
        --glob '$path_pattern'"
    
    [ -n "$max_results" ] && rg_cmd="$rg_cmd --max-count $max_results"
    
    echo "=== Files matching: $path_pattern ==="
    rg --files --glob "$path_pattern" | head -20
    
    echo -e "\n=== Search Results ==="
    eval "$rg_cmd ."
}

# Reload shell
source ~/.bashrc  # or source ~/.zshrc

Usage

sgrep <path_pattern> <search_pattern> [context_lines] [max_results]

Parameters

  • path_pattern (required): Glob pattern to filter files (e.g., *.py, src/**/*.ts)
  • search_pattern (required): Text or regex pattern to search for
  • context_lines (optional): Number of lines above/below match (default: 3)
  • max_results (optional): Maximum matches per file (default: all)

Examples

Basic Usage

# Search for "surreal" in TypeScript files under app/, 5 lines context
sgrep "app/**/*.ts" "surreal" 5

# Search for TODO in Python files, default 3 lines context
sgrep "src/**/*.py" "TODO"

# Search in all JavaScript files in current directory
sgrep "*.js" "function"

Advanced Patterns

# Search for async functions in nested TypeScript files
sgrep "**/*.ts" "async function" 4

# Find API endpoints in route files
sgrep "routes/**/*.py" "@app\.(get|post)" 5

# Search for imports with 2 lines context, max 10 results
sgrep "src/**/*.ts" "import.*from" 2 10

# Find environment variables usage
sgrep "**/*.{ts,js}" "process\.env\." 3

# Search for React hooks in component files
sgrep "components/**/*.tsx" "use[A-Z]\w+" 4 20

Real-World Scenarios

# Find all database queries in models
sgrep "models/**/*.py" "db\.(query|execute|fetch)" 5

# Locate error handling in services
sgrep "services/**/*.ts" "try\s*{|catch\s*\(" 3

# Find all test files with specific test case
sgrep "**/*.test.ts" "describe\('User'" 4

# Search for configuration usage
sgrep "**/*.{yml,yaml}" "database:" 2

# Find deprecated function usage
sgrep "src/**/*" "@deprecated" 5 15

Agent-Friendly Examples

# Understanding how a module is used
sgrep "**/*.ts" "import.*surreal" 3

# Finding implementation of a specific function
sgrep "**/*.py" "def process_data" 5

# Locating API route definitions
sgrep "routes/**/*" "router\.(get|post|put|delete)" 4

# Checking error handling patterns
sgrep "src/**/*.ts" "throw new Error" 3 20

# Finding configuration references
sgrep "**/*.{ts,py}" "config\." 2 10

Output Format

The function provides two sections:

  1. Files matching - Lists up to 20 files matching the path pattern
  2. Search Results - Shows matches with:
    • File path as heading
    • Line numbers
    • Context lines above and below
    • Syntax highlighting (colored output)

Tips

  • Use ** for recursive directory matching
  • Use {ext1,ext2} for multiple extensions: **/*.{ts,tsx,js}
  • Regex patterns supported in search_pattern
  • Use quotes around patterns with special characters
  • Combine with | less -R for paginated output with colors: sgrep "**/*.py" "TODO" | less -R

Troubleshooting

No results found:

  • Check if ripgrep is installed: rg --version
  • Verify path pattern matches actual file structure
  • Try simpler patterns first (e.g., *.py before src/**/*.py)

Too many results:

  • Use the max_results parameter to limit output
  • Make search pattern more specific
  • Narrow down the path pattern

Pattern not matching:

  • Escape special regex characters: \(, \[, \.
  • Use single quotes to prevent shell expansion
  • Test pattern with plain rg first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment