Install ast-grep on Ubuntu 24.04

Install ast-grep on Ubuntu 24.04

The ast-grep is a tool designed for code searching and manipulation, utilizing abstract syntax trees (ASTs) to understand and process code more intelligently than traditional text-based grep tools. This tutorial demonstrates how to install ast-grep on Ubuntu 24.04.

Install ast-grep

Download ast-grep archive file from releases page of GitHub repository:

wget -qO ast-grep.zip https://github.com/ast-grep/ast-grep/releases/latest/download/app-x86_64-unknown-linux-gnu.zip

Extract executable to /usr/local/bin directory:

sudo unzip -q ast-grep.zip -d /usr/local/bin sg

Verify the installation by checking the version of ast-grep:

sg --version

Since the archive file is unnecessary now, you can remove it:

rm -rf ast-grep.zip

Testing ast-grep

Create a Python file for testing purposes:

nano test.py

Add the following code:

def add(x):
    return x + 1

y = add(2)
print(y)

The easiest method to rewrite code is by using the --rewrite option with the sg run command. This option accepts a string argument that defines the new code to replace the matched pattern. For example, to change all instances of the identifier add to increment, you can run:

sg run --pattern 'add' --rewrite 'increment' --lang python -U

Code after modification:

def increment(x):
    return x + 1

y = increment(2)
print(y)

Uninstall ast-grep

To uninstall ast-grep, delete the executable file:

sudo rm -rf /usr/local/bin/sg

Leave a Comment

Cancel reply

Your email address will not be published.