MST
星途 面试题库

面试题:Bash命令替换与变量替换的高级优化与嵌套

编写一个Bash函数,该函数接收两个参数,第一个参数为目录路径 $DIR_PATH,第二个参数为文件扩展名 $EXT。函数需要通过命令替换,在指定目录及其子目录中查找所有指定扩展名的文件,并计算这些文件的总大小(以字节为单位)。利用变量替换将这些文件按大小从大到小排序后,输出文件名及其大小。同时,要确保在处理过程中能够处理文件名包含特殊字符的情况,写出完整的函数实现。
17.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
calculate_file_size() {
    local DIR_PATH=$1
    local EXT=$2
    local files=()
    local total_size=0

    # 使用find命令查找指定目录及其子目录中指定扩展名的文件,并处理文件名包含特殊字符的情况
    while IFS= read -r -d '' file; do
        files+=("$file")
        local file_size=$(stat -c %s "$file")
        total_size=$((total_size + file_size))
    done < <(find "$DIR_PATH" -name "*.$EXT" -type f -print0)

    # 按文件大小从大到小排序
    local sorted_files=($(for file in "${files[@]}"; do echo $(stat -c %s "$file") "$file"; done | sort -nr | cut -d ' ' -f 2-))

    echo "Total size of files with extension $EXT in $DIR_PATH: $total_size bytes"
    echo "Files sorted by size (descending):"
    for file in "${sorted_files[@]}"; do
        local file_size=$(stat -c %s "$file")
        echo "$file: $file_size bytes"
    done
}