Shell 脚本多次附加文件名?

问题描述 投票:0回答:1

很抱歉提出新手问题。有谁知道如何“修复”这个 shell 脚本,以便它不会多次在子文件夹中追加文件?

#!/bin/bash

# Function to append compression type to filename
append_compression_type() {
    local file="$1"
    local compression_type="$2"

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

    # Append compression type to filename
    local new_filename="${filename_no_ext}_${compression_type}.${file##*.}"

    # Rename the file
    mv "$file" "$new_filename"

    echo "Renamed $file to $new_filename"
}

# Recursive function to process images in a directory
process_directory() {
    local directory="$1"

    # Find all image files in the directory
    find "$directory" -type f \( -iname "*.dds" \) | while read -r image_file; do
        # Get the compression type of the image
        local compression_type=$(identify -format '%C' "$image_file" 2>/dev/null)

        # If compression type is not empty
        if [ -n "$compression_type" ]; then
            append_compression_type "$image_file" "$compression_type"
        fi
    done

    # Process subdirectories
    find "$directory" -mindepth 1 -type d | while read -r subdirectory; do
        process_directory "$subdirectory"
    done
}

# Start processing from the current directory
process_directory "."

它适用于与脚本位于同一文件夹中的任何文件,但子文件夹中的任何文件都会如前所述多次附加。

sh
1个回答
0
投票

此行不需要

find
表达式中的括号:

find "$directory" -type f \( -iname "*.dds" \) | while read -r image_file; do

您的意思是在括号内有一个更复杂的表达式吗?

多次处理文件的原因是上面的

find
命令不仅输出与
*.dds
中的
$directory
glob 匹配的文件,而且还输出所有子目录。因此,当您执行此操作时,您将第二次处理每个直接子目录中的
*.dds
文件,并第三次处理第二级子目录中的每个
*.dds
文件,等等:

find "$directory" -mindepth 1 -type d | while read -r subdirectory; do

如果您确实想独立于其他目录处理每个目录,请在第一个

-maxdepth 1
命令中添加
find
。或者,只需省略第二个
find
块。

© www.soinside.com 2019 - 2024. All rights reserved.