如何验证文件夹大小(如500K、1.1M)是否小于2MB?
验证文件夹大小是否≤2MB的实现方法
核心逻辑
先将带单位的大小字符串(如500K、1.5M)转换为统一的MB数值,再与2MB进行比较,根据结果输出pass或fail。
Python 实现示例
def check_folder_size(folder_size): # 分离数值与单位 num = float(''.join(filter(lambda c: c.isdigit() or c == '.', folder_size))) unit = ''.join(filter(lambda c: c.isalpha(), folder_size)).upper() # 转换为MB单位 if unit == 'K': size_mb = num / 1024 elif unit == 'M': size_mb = num # 如需支持其他单位(如G),可在此扩展分支 # 判定并输出结果 print("pass" if size_mb <= 2 else "fail") # 测试用例 check_folder_size("1M") # 输出 pass check_folder_size("500K") # 输出 pass check_folder_size("2.5M") # 输出 fail
Shell 脚本实现示例
check_folder_size() { local folder_size="$1" # 提取数值和单位 local num=$(echo "$folder_size" | sed 's/[A-Za-z]//g') local unit=$(echo "$folder_size" | sed 's/[0-9.]//g' | tr '[:lower:]' '[:upper:]') # 转换为MB if [ "$unit" = "K" ]; then local size_mb=$(echo "scale=4; $num / 1024" | bc) elif [ "$unit" = "M" ]; then local size_mb="$num" fi # 比较并输出结果 if (( $(echo "$size_mb <= 2" | bc -l) )); then echo "pass" else echo "fail" fi } # 测试用例 check_folder_size "1M" check_folder_size "500K" check_folder_size "2.1M"
内容的提问来源于stack exchange,提问作者iltech
相关产品推荐
相关产品推荐

