#!/bin/bash

# 检查输入参数是否正确
if [ "$#" -lt 3 ]; then
  echo "Usage: $0 <root_directory> <old_string> <replace_string> [1]"
  exit 1
fi

root_directory=$1
old_string=$2
replace_string=$3
confirm_flag=${4:-"0"}
#echo $confirm_flag
# 默认情况下不进行确认
confirm_replace=false
# 检查第四个参数是否为"1",如果是,则设置为true
if [ "$confirm_flag" == "1" ]; then
  confirm_replace=true
fi

# 确保输入的路径是绝对路径
root_directory=$(cd "$root_directory"; pwd)
echo "root_directory: ${root_directory}"

for file in "$root_directory"/*
do
  # 使用sed命令替换文件名中的特定字符串
  # 使用basename命令获取不包含路径的文件名
  newname=$(basename "$file" | sed "s/$old_string/$replace_string/")
  
  # 检查新文件名是否与原文件名不同,如果是则重命名
  if [ "$newname" != "$(basename "$file")" ]; then
    echo "$file => $root_directory/$newname"
    if $confirm_replace; then
        mv "$file" "$root_directory/$newname"
        #echo "执行替换了"
    fi
  fi
done

./rename_files.sh 目录 原字符串 替换后的字符串 1

 

shell脚本 批量修改文件名, 遍历文件夹中的*.zip, 修改文件名, 替换文件名中的abc为test, 替换dda为s5