BASH
Recursive Text Find and Replace
Efficiently update text strings across multiple files and directories in your project. Ideal for refactoring variable names, updating URLs, or changing configuration values recursively.
#!/bin/bash
# Directory to start searching from (e.g., '.', './src', '/var/www/html')
SEARCH_DIR="./config"
# Old text to find (regex allowed, but be careful with special characters)
OLD_TEXT="old_api_url.com"
# New text to replace with
NEW_TEXT="new_production_api.com"
# File extensions to include, comma-separated (e.g., "js,php,css,html,json,yml")
FILE_EXTENSIONS="js,json,php,html"
# --- Script Start ---
if [ ! -d "$SEARCH_DIR" ]; then
echo "Error: Search directory '$SEARCH_DIR' does not exist." >&2
exit 1
fi
echo "Starting find and replace in '$SEARCH_DIR' for files with extensions: $FILE_EXTENSIONS"
echo "Replacing '$OLD_TEXT' with '$NEW_TEXT'"
# Use find to locate files with specified extensions and xargs to pass them to sed
# -type f: only files
# -regex: matches files based on a regular expression for their full path
# -print0: prints filenames separated by a null character (safe for filenames with spaces)
# xargs -0: reads null-separated arguments
# sed -i: modifies files in place
# 's|OLD_TEXT|NEW_TEXT|g': performs a global replacement. '|' is used as a delimiter
# to avoid issues if OLD_TEXT or NEW_TEXT contain '/'.
find "$SEARCH_DIR" -type f -regex ".*\.\(${FILE_EXTENSIONS//,/\|}\\)" -print0 | xargs -0 sed -i "s|${OLD_TEXT}|${NEW_TEXT}|g"
# Note for macOS users: BSD sed requires an argument for -i, even if empty.
# The command for macOS would typically be:
# find "$SEARCH_DIR" -type f -regex ".*\.\(${FILE_EXTENSIONS//,/\|}\\)" -print0 | xargs -0 sed -i '' "s|${OLD_TEXT}|${NEW_TEXT}|g"
echo "Replacement complete."
echo "It is recommended to review changed files and commit the changes."
How it works: This powerful script facilitates a project-wide find and replace operation. It uses `find` to recursively locate all files within a `SEARCH_DIR` that match a set of specified `FILE_EXTENSIONS`. The `find` command's output (null-separated filenames for safety) is then piped to `xargs -0`, which executes `sed` for each file. `sed -i` performs an in-place substitution, replacing all occurrences (`g` flag) of `OLD_TEXT` with `NEW_TEXT`. The `|` character is used as a custom delimiter for `sed`'s substitute command to prevent conflicts if the text strings contain forward slashes. A note is included for macOS users regarding the `sed -i` syntax.