说明

编写一个 shell 脚本,实现当前目录下图片文件的顺序重命名。这个脚本将遍历当前目录下的所有图片文件(如 .jpg, .jpeg, .png, .gif 等),然后按照顺序从 1 开始重命名。

创建 shell 脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/bin/bash

# 图片文件重命名脚本 - 从1开始按顺序编号
# 使用方法: ./rename_images.sh [扩展名1 扩展名2 ...]
# 默认扩展名: jpg jpeg png gif

# 设置默认图片扩展名,如果提供了参数则使用参数
if [ $# -eq 0 ]; then
extensions=("jpg" "jpeg" "png" "gif")
else
extensions=("$@")
fi

# 创建一个数组来存储所有图片文件
image_files=()

# 收集所有指定扩展名的图片文件
for ext in "${extensions[@]}"; do
for file in *."$ext"; do
if [ -f "$file" ]; then
image_files+=("$file")
fi
done
done

# 如果没有找到图片文件,退出脚本
if [ ${#image_files[@]} -eq 0 ]; then
echo "没有找到指定类型的图片文件"
exit 1
fi

# 按文件名排序
IFS=$'\n' sorted_files=($(sort <<<"${image_files[*]}"))
unset IFS

# 询问用户是否继续
echo "找到 ${#sorted_files[@]} 个图片文件将被重命名:"
for ((i=0; i<${#sorted_files[@]}; i++)); do
printf "%d: %s\n" $((i+1)) "${sorted_files[$i]}"
done

read -p "是否继续重命名? (y/n): " confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
echo "操作已取消"
exit 0
fi

# 执行重命名操作
counter=1
for file in "${sorted_files[@]}"; do
# 获取文件扩展名
ext="${file##*.}"
# 构建新文件名
new_name="${counter}.${ext}"

# 检查新文件名是否已存在
while [ -f "$new_name" ]; do
counter=$((counter+1))
new_name="${counter}.${ext}"
done

# 执行重命名
mv "$file" "$new_name"
echo "已重命名: $file -> $new_name"
counter=$((counter+1))
done

echo "重命名完成!共处理 ${#sorted_files[@]} 个文件"

这个脚本具有以下特点:

  1. 可自定义扩展名 - 默认处理 jpg、jpeg、png 和 gif 格式的图片,也可以通过参数指定其他格式
  2. 安全措施 - 在执行重命名前会显示所有找到的文件,并要求用户确认
  3. 避免冲突 - 如果新文件名已存在,会自动递增编号以避免覆盖
  4. 文件排序 - 按文件名排序后再重命名,确保顺序合理

使用方法

  1. 将脚本保存为 rename_images.sh
  2. 给脚本添加执行权限:chmod +x rename_images.sh
  3. 运行脚本:
    • 默认执行:./rename_images.sh
    • 指定扩展名:./rename_images.sh jpg png webp

注意事项

  • 脚本会在当前目录下执行操作,请确保在正确的目录下运行
  • 重命名操作不可撤销,请先备份重要文件
  • 如果有大量文件,建议先使用 ls -1 | wc -l 检查文件数量
  • 如果需要更复杂的重命名规则,比如添加前缀或后缀,可以对脚本进行相应修改