Script to change string in all files in directory

#!/bin/bash

# Function to display colored diff
show_diff() {
    local old=$1
    local new=$2
    local file=$3

    echo -e "\nChanges in $file:"
    grep -n "$old" "$file" | while read -r line; do
        lineno=$(echo "$line" | cut -d: -f1)
        original=$(echo "$line" | cut -d: -f2-)
        modified=$(echo "$original" | sed "s|$old|$new|g")
        echo -e "$lineno: \033[0;31m-$original\033[0m"
        echo -e "$lineno: \033[0;32m+$modified\033[0m"
    done
}

# Get directory to search in (defaults to current)
read -p "Enter directory to search in (default: current): " search_dir
search_dir=${search_dir:-.}

# Verify directory exists
if [ ! -d "$search_dir" ]; then
    echo "Error: Directory '$search_dir' does not exist."
    exit 1
fi

# Get old and new domains
read -p "Enter old domain (e.g., http://domain.tld): " old_domain
read -p "Enter new domain (e.g., http://newdomain.tld): " new_domain

if [ -z "$old_domain" ] || [ -z "$new_domain" ]; then
    echo "Error: Both domains must be provided."
    exit 1
fi

# Find all files containing the old domain
echo -e "\nSearching for files containing '$old_domain' in '$search_dir'..."
files=$(grep -rl "$old_domain" "$search_dir" 2>/dev/null)

if [ -z "$files" ]; then
    echo "No files found containing '$old_domain'."
    exit 0
fi

# Show files that will be modified
echo -e "\nThe following files will be modified:"
echo "$files" | nl

# Preview changes
echo -e "\nPreview of changes:"
for file in $files; do
    show_diff "$old_domain" "$new_domain" "$file"
done

# Ask for confirmation
read -p $'\nDo you want to apply these changes? (y/n): ' confirm
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
    echo "Changes not applied."
    exit 0
fi

# Make changes
echo -e "\nApplying changes..."
for file in $files; do
    sed -i "s|$old_domain|$new_domain|g" "$file"
    echo "Updated: $file"
done

echo -e "\nAll changes have been applied."