BASH
Find and Replace Text Recursively in Files
Perform a powerful recursive find and replace operation across multiple files in a directory using Bash with `find` and `sed` for quick code refactoring.
#!/bin/bash
# Directory to start searching from
SEARCH_DIR="."
# Original string to find
FIND_STRING="old_text"
# Replacement string
REPLACE_STRING="new_text"
# File types to include (e.g., "*.js", "*.html", "*.php"). Use "*" for all files.
FILE_PATTERN="*.txt"
echo "Searching for '$FIND_STRING' and replacing with '$REPLACE_STRING' in '$SEARCH_DIR' (files matching '$FILE_PATTERN')..."
# Use 'find' to locate files and 'sed' to perform in-place replacement
find "$SEARCH_DIR" -type f -name "$FILE_PATTERN" -exec sed -i "s/$FIND_STRING/$REPLACE_STRING/g" {} \;
echo "Replacement complete."
How it works: This script efficiently finds specific text within files and replaces it with new text, recursively traversing a directory structure. It leverages `find` to locate files matching a specified pattern and then pipes these files to `sed` for an in-place (`-i`) global (`g`) substitution. This is incredibly useful for project-wide refactoring or bulk content updates.