BASH
Find and Replace Text in Project Files
A powerful bash script to recursively find files matching a pattern and replace text within them, useful for refactoring or updating configurations across a web project.
#!/bin/bash
# Usage: ./replace_text.sh <directory> <find_string> <replace_string> <file_extension>
DIRECTORY=$1
FIND_STRING=$2
REPLACE_STRING=$3
FILE_EXTENSION=$4
if [ -z "$DIRECTORY" ] || [ -z "$FIND_STRING" ] || [ -z "$REPLACE_STRING" ] || [ -z "$FILE_EXTENSION" ]; then
echo "Usage: $0 <directory> <find_string> <replace_string> <file_extension>"
echo "Example: $0 . 'old_variable' 'new_variable' 'js'"
exit 1
fi
echo "Searching for files with extension .$FILE_EXTENSION in $DIRECTORY and replacing '$FIND_STRING' with '$REPLACE_STRING'...
"
# Using find and xargs for efficiency, sed for replacement
find "$DIRECTORY" -type f -name "*.$FILE_EXTENSION" -print0 | xargs -0 sed -i "s/$FIND_STRING/$REPLACE_STRING/g"
echo "Replacement complete."
How it works: This script utilizes `find` to locate all files with a specified extension within a given directory (and its subdirectories). It then pipes the list of found files to `xargs -0` to handle filenames with special characters, which in turn executes `sed -i` on each file. `sed -i` performs an in-place replacement of all occurrences (`g` flag) of the `FIND_STRING` with the `REPLACE_STRING`. This is invaluable for refactoring variable names, updating configuration strings, or modifying content across an entire codebase.