You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本重复添加文件名后缀问题:如何修复子目录文件重复处理

修复Shell脚本避免重复添加文件名后缀

问题根源

原脚本存在两个导致重复添加后缀的问题:

  1. find "$directory" -type f \( -iname "*.dds" \)默认会递归扫描当前目录及所有子目录的文件,同时脚本又手动递归调用process_directory处理子目录,导致子目录中的文件被多次扫描处理,每次处理都追加后缀。
  2. 没有判断文件是否已经添加过压缩类型后缀,即使处理过一次,再次扫描到还是会重复添加。

修复方案一:保留递归函数结构,避免重复扫描

修改后的完整脚本:

#!/bin/bash

# 给文件名追加压缩类型后缀
append_compression_type() {
    local file="$1"
    local compression_type="$2"

    # 分离文件名和扩展名
    local filename_no_ext="${file%.*}"
    local extension="${file##*.}"

    # 检查是否已经添加过该压缩类型后缀,避免重复处理
    if [[ "$filename_no_ext" == *"_${compression_type}" ]]; then
        echo "跳过 $file: 已包含${compression_type}后缀"
        return
    fi

    # 生成新文件名并重命名
    local new_filename="${filename_no_ext}_${compression_type}.${extension}"
    mv "$file" "$new_filename"

    echo "已重命名 $file 为 $new_filename"
}

# 递归处理目录
process_directory() {
    local directory="$1"

    # 只处理当前目录下的dds文件,-maxdepth 1限制不递归扫描
    find "$directory" -maxdepth 1 -type f \( -iname "*.dds" \) | while read -r image_file; do
        # 获取图片压缩类型
        local compression_type=$(identify -format '%C' "$image_file" 2>/dev/null)

        if [ -n "$compression_type" ]; then
            append_compression_type "$image_file" "$compression_type"
        fi
    done

    # 只处理当前目录下的直接子目录
    find "$directory" -mindepth 1 -maxdepth 1 -type d | while read -r subdirectory; do
        process_directory "$subdirectory"
    done
}

# 从当前目录开始处理
process_directory "."

关键修改点:

  • 在两个find命令中添加-maxdepth 1:第一个限制只处理当前目录的文件,第二个只找当前目录的直接子目录,彻底避免重复扫描。
  • 新增后缀重复检查:在重命名前判断文件名是否已经包含目标压缩类型后缀,防止意外重复处理。

修复方案二:简化结构,用find一次性递归处理

如果不需要保留递归函数结构,这个方案更简洁:

#!/bin/bash

# 给文件名追加压缩类型后缀
append_compression_type() {
    local file="$1"
    local compression_type="$2"

    local filename_no_ext="${file%.*}"
    local extension="${file##*.}"

    # 检查是否已处理过
    if [[ "$filename_no_ext" == *"_${compression_type}" ]]; then
        echo "跳过 $file: 已处理"
        return
    fi

    local new_filename="${filename_no_ext}_${compression_type}.${extension}"
    mv "$file" "$new_filename"
    echo "已重命名 $file 为 $new_filename"
}

# 一次性递归遍历所有dds文件,避免重复处理
find "." -type f -iname "*.dds" | while read -r image_file; do
    local compression_type=$(identify -format '%C' "$image_file" 2>/dev/null)
    if [ -n "$compression_type" ]; then
        append_compression_type "$image_file" "$compression_type"
    fi
done

这个方案直接用find递归遍历所有目标文件,不需要手动维护递归逻辑,同时保留重复检查,确保每个文件只处理一次。


内容的提问来源于stack exchange,提问作者D3SOL4TE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 07:03:33