BASH

Find and Replace Text Across Multiple Files in Bash

Efficiently find and replace specific text strings across multiple files within a directory and its subdirectories using a powerful bash script with `find` and `sed`.

#!/bin/bash

# Configuration
SEARCH_DIR="."           # Directory to start the search (e.g., '.', './src')
FILE_EXTENSION="php"     # File extension to target (e.g., 'html', 'js', 'css', '*')
OLD_STRING="old_function_name" # The string to find
NEW_STRING="new_function_name" # The string to replace with

echo "Searching for '$OLD_STRING' and replacing with '$NEW_STRING' in files with .$FILE_EXTENSION extension within '$SEARCH_DIR'..."

# Use find to locate files and sed to perform the replacement
# -type f: Only consider files
# -name "*.$FILE_EXTENSION": Match files with the specified extension
# -exec ... +: Execute the command for multiple found files at once
# sed -i: Perform in-place editing (create backup with -i.bak if supported/desired)
# 's/old/new/g': Substitution command: 's'ubstitute 'old' with 'new', 'g'lobally (all occurrences on line)
find "$SEARCH_DIR" -type f -name "*.$FILE_EXTENSION" -exec sed -i "s/$OLD_STRING/$NEW_STRING/g" {} +

if [ $? -eq 0 ]; then
    echo "Replacement completed successfully."
else
    echo "An error occurred during replacement. Check logs."
fi

# Important Note: sed -i on macOS behaves differently than GNU/Linux.
# On macOS, `sed -i ''` will edit in-place without backup.
# `sed -i '.bak'` will create backup files.
# For cross-platform compatibility, consider using `perl -pi -e 's/OLD/NEW/g' filenames`
# or ensure you have GNU sed installed (e.g., `brew install gnu-sed` on macOS).
How it works: This script leverages `find` and `sed` to perform a powerful search-and-replace operation across multiple files. `find` locates files based on a specified directory and file extension, and then `sed -i` executes an in-place substitution, replacing all occurrences of `OLD_STRING` with `NEW_STRING`. The `g` flag in `s/OLD/NEW/g` ensures global replacement on each line found within the targeted files.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs