BASH
Find and Replace Text in Multiple Files
Perform quick and powerful text replacements across numerous files in your project using a single Bash command, ideal for refactoring or bulk updates.
#!/bin/bash
# Configuration
SEARCH_DIR="." # Directory to search in (e.g., '.', './src', '/var/www/myproject')
FIND_TEXT="old_string_to_find"
REPLACE_TEXT="new_string_to_replace"
FILE_PATTERN="*.php" # Files to target (e.g., "*.php", "*.js", "*.html", "*")
# Use 'g' for global replacement (all occurrences on a line)
# Use 'i' for case-insensitive search (if needed, add 'i' after 'g')
SED_OPTIONS="g"
echo "Searching for '$FIND_TEXT' and replacing with '$REPLACE_TEXT' in files matching '$FILE_PATTERN' within '$SEARCH_DIR'..."
# Confirm before proceeding, especially for sensitive operations
read -p "Are you sure you want to proceed? (y/N): " -n 1 -r
echo # Newline for better output
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Operation cancelled."
exit 1
fi
# Find files and use sed for in-place replacement
# Using 'find' with '-exec' and 'sed -i' for robustness.
# The 'sed -i.bak' creates a backup; remove '.bak' to disable.
find "$SEARCH_DIR" -type f -name "$FILE_PATTERN" -print0 | while IFS= read -r -d $'\0' file; do
echo "Processing file: $file"
# Escape special characters in FIND_TEXT and REPLACE_TEXT for sed regex
ESCAPED_FIND=$(echo "$FIND_TEXT" | sed 's/[&/\\]/\\&/g')
ESCAPED_REPLACE=$(echo "$REPLACE_TEXT" | sed 's/[&/\\]/\\&/g')
# Use sed for in-place replacement (creates .bak files)
# sed -i "$SED_OPTIONS" "s/$ESCAPED_FIND/$ESCAPED_REPLACE/$SED_OPTIONS" "$file"
# To avoid creating backup files (use with caution, can't undo easily):
sed -i "" "s/$ESCAPED_FIND/$ESCAPED_REPLACE/$SED_OPTIONS" "$file" # For macOS/BSD sed
# For GNU sed (Linux): sed -i "s/$ESCAPED_FIND/$ESCAPED_REPLACE/$SED_OPTIONS" "$file"
if [ $? -eq 0 ]; then
echo " Replaced in $file"
else
echo " ERROR: Failed to replace in $file"
fi
done
echo "Text replacement finished."
How it works: This script enables you to find specific text and replace it with new text across multiple files within a specified directory. It uses `find` to locate files matching a `FILE_PATTERN` and then employs `sed` for in-place text replacement. The script includes a confirmation prompt and handles escaping special characters for `sed` to prevent issues with regex. Note the different `sed -i` syntax for macOS/BSD vs. GNU/Linux.