BASH
Search and Replace Text Recursively Across Files
Perform powerful global search and replace operations in your codebase using a bash script. Recursively update text patterns across multiple files with sed, ideal for refactoring.
#!/bin/bash
# Configuration
SEARCH_STRING="old_variable_name"
REPLACE_STRING="new_variable_name"
TARGET_DIR="./src"
FILE_EXTENSION="php"
# Confirmation prompt
read -p "Are you sure you want to replace all occurrences of '$SEARCH_STRING' with '$REPLACE_STRING' in '$TARGET_DIR/*.${FILE_EXTENSION}'? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
echo "Operation cancelled."
exit 1
fi
echo "Searching for '$SEARCH_STRING' and replacing with '$REPLACE_STRING' in '$TARGET_DIR/**/*.${FILE_EXTENSION}'..."
# Find files and perform in-place replacement using sed
# -type f: Only files
# -name "*.${FILE_EXTENSION}": Filter by extension
# -exec sed -i 's|SEARCH_STRING|REPLACE_STRING|g' {} +: In-place replace (using | as delimiter)
find "$TARGET_DIR" -type f -name "*.${FILE_EXTENSION}" -exec sed -i "s|${SEARCH_STRING}|${REPLACE_STRING}|g" {} +
if [ $? -eq 0 ]; then
echo "Replacement completed successfully."
else
echo "An error occurred during replacement."
exit 1
fi
How it works: This bash script facilitates a recursive search and replace operation across files within a specified directory. It uses `find` to locate files matching a pattern (e.g., by extension) and `sed` to perform the in-place text replacement. This is highly useful for large-scale refactoring or updating deprecated strings across a codebase. A confirmation prompt is included for safety, and an alternative `sed` delimiter is used to handle potential slashes in search/replace strings.