#!/bin/bash

# 检查参数是否足够
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <directory> <old_value> <new_value>"
    echo "Example: $0 /path/to/dir old_string new_string"
    exit 1
fi

# 参数赋值
DIR=$1
OLD_VALUE=$2
NEW_VALUE=$3

# 检查目标目录是否存在
if [ ! -d "$DIR" ]; then
    echo "Error: Directory '$DIR' does not exist."
    exit 1
fi

# 初始化统计变量
TOTAL_FILES=0
TOTAL_LINES=0

# 查找包含目标值的文件
FILES=$(find "$DIR" -type f -exec grep -l "$OLD_VALUE" {} \;)

if [ -z "$FILES" ]; then
    echo "No files found containing the value '$OLD_VALUE'."
    exit 0
fi

# 替换每个文件中的目标值
for FILE in $FILES; do
    echo "Processing: $FILE"

    # 备份原文件
    cp "$FILE" "$FILE.bak"

    # 替换旧值为新值，并统计修改的行数
    MODIFIED_LINES=$(grep -c "$OLD_VALUE" "$FILE")
    sed -i "s/$OLD_VALUE/$NEW_VALUE/g" "$FILE"

    # 更新统计信息
    TOTAL_LINES=$((TOTAL_LINES + MODIFIED_LINES))
    TOTAL_FILES=$((TOTAL_FILES + 1))
done

# 显示总结信息
echo "Replacement completed."
echo "Total files modified: $TOTAL_FILES"
echo "Total lines replaced: $TOTAL_LINES"
echo "Backup files have .bak extension."

# 询问用户是否删除备份文件
read -p "Do you want to delete all backup files (.bak)? (y/N): " DELETE_BACKUP

case "$DELETE_BACKUP" in
    y|Y)
        # 删除所有备份文件
        find "$DIR" -type f -name "*.bak" -exec rm -f {} \;
        echo "All backup files have been deleted."
        ;;
    *)
        echo "Backup files are kept in the directory."
        ;;
esac

