#!/bin/bash # 文件名替换脚本:将文件名中的指定旧字符串替换为新字符串 # 用法:./rename_script.sh /目标/目录/路径 "旧字符串" "新字符串" # 检查参数数量 if [ $# -ne 3 ]; then echo "错误:参数数量不正确" echo "用法: $0 /目录/路径 \"旧字符串\" \"新字符串\"" exit 1 fi target_dir="$1" old_str="$2" new_str="$3" # 检查目录是否存在 if [ ! -d "$target_dir" ]; then echo "错误:目录 '$target_dir' 不存在" exit 1 fi # 设置安全选项 set -euo pipefail IFS=$'\n' # 正确处理文件名中的空格 echo "开始处理目录: $target_dir" echo "替换规则: '$old_str' -> '$new_str'" echo "----------------------------------------" # 查找所有包含旧字符串的文件名 counter=0 while IFS= read -r -d $'\0' file; do # 获取文件名和目录路径 dirpath=$(dirname "$file") filename=$(basename "$file") # 检查是否需要替换 if [[ "$filename" == *"$old_str"* ]]; then # 执行替换 new_name="${filename//$old_str/$new_str}" new_path="$dirpath/$new_name" # 跳过名称未变化的文件 if [[ "$filename" == "$new_name" ]]; then continue fi # 避免覆盖已存在文件 if [ -e "$new_path" ]; then echo "警告: 跳过 '$file' -> '$new_name' (目标文件已存在)" continue fi # 执行重命名 mv -v "$file" "$new_path" ((counter++)) fi done < <(find "$target_dir" -type f -print0 2>/dev/null) echo "----------------------------------------" echo "完成! 已重命名 $counter 个文件"