Skip to main content

Code Refactoring with rg

rg is the ideal first step in any project-wide refactoring — it finds precisely which files need to change, letting a replacement tool do the editing.

The Two-Step Pattern

rg -l "old_pattern" → list of files → sed / sd / perl

Step 1: Find & Preview

Always preview before changing anything:

# See every occurrence of the old function name
rg "processUserData" src/

# Preview the surrounding context
rg -C 2 "processUserData" src/

Step 2: Replace with sed

# Replace in all files containing the pattern
rg -l "processUserData" src/ | xargs sed -i 's/processUserData/handleUserPayload/g'

Step 2 (Alternative): Replace with sd

sd (the Rust sed alternative) has simpler syntax and handles special characters better:

rg -l "processUserData" src/ | xargs sd "processUserData" "handleUserPayload"

Multi-File Rename (Function Signature Change)

# Old: getUserById(id, callback)
# New: fetchUser(id) (remove callback parameter)

rg -l "getUserById" src/ | xargs sd "getUserById\(\w+, \w+\)" "fetchUser(id)"

Renaming Import Paths

After moving a module:

# Change import source from old path to new path
rg -l "from '../utils/helpers'" src/ | \
xargs sed -i "s|from '../utils/helpers'|from '../shared/helpers'|g"

Validating Refactors with rg

After the replacement, verify nothing was missed and nothing was broken:

# Old name should no longer exist
rg "processUserData" src/
# (Should return no output)

# New name should be widely present
rg -c "handleUserPayload" src/